SDK 2.2 を使用して、ConnectivityManager クラスのメソッド setMobileDataEnabled を使用しようとしています。http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2.1_r1/android/net/ConnectivityManager.java/?v=sourceによると、 このメソッドは宣言されていますpublic but with @hide は、SDK および Eclipse では使用できません。
非表示をバイパスするために、モバイルデータ接続のオン/オフを切り替える次の関数を作成しました。
public void setMobileData(boolean toBeEnabled){
Object myObj= getSystemService(CONNECTIVITY_SERVICE);
ConnectivityManager cm = (ConnectivityManager) myObj;
Class c = null;
try {
c = Class.forName(cm.getClass().getName());
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Method m = null;
try {
m = c.getDeclaredMethod("getMobileDataEnabled");
} catch (SecurityException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (NoSuchMethodException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Object mobileDataEnabled=null;
if (m!=null){
m.setAccessible(true);
Type res_of_m= m.getGenericReturnType();
Type[] pars_of_m= m.getGenericParameterTypes();
try {
mobileDataEnabled = (m.invoke(cm));
if (mobileDataEnabled!=null)
if (mobileDataEnabled.equals(!toBeEnabled)){
Method m2 = null;
try {
int index=0;
boolean method_found=false;
Method[] available_methods= c.getDeclaredMethods();
for (Method method : available_methods) {
// following line doesn't work
// method.getName()=="setMobileDataEnabled"
if (method.getName().contains("setMobileDataEnabled"))
{
method_found=true;
}
if (method_found==false)
index++;
}
// following line doesn't work
//m2 = c.getDeclaredMethod("setMobileDataEnabled");
m2 = (c.getDeclaredMethods())[index];
if (m2!=null){
m2.setAccessible(true);
m2.invoke(cm,toBeEnabled);
}
} catch (SecurityException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (InvocationTargetException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
それを機能させるために、マニフェストに android.permission.WRITE_SECURE_SETTINGS" も追加し、Android に従って /system/app にインストールしました: ファームウェアにアプリを追加し、 WRITE_SECURE_SETTINGS を使用します。
誰かがより良い方法を知っていますか?