我一直使用这段代码通过编程方式启用移动数据:
ConnectivityManager conman = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); @SuppressWarnings("rawtypes") final Class conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); @SuppressWarnings("rawtypes") final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); @SuppressWarnings("unchecked") final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager,true);
这一点很好,除了现在在Android 4.4.2上,我得到这个例外:
java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] at java.lang.Class.getConstructorOrMethod(Class.java:472) at java.lang.Class.getDeclaredMethod(Class.java:640) at com.test.auto3gPro.ClasseConnessione.settaConnessione(ClasseConnessione.java:48) at com.test.auto3gPro.receiver.ScreenBroadcastReceiver.onReceive(ScreenBroadcastReceiver.java:108) at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5081) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method)
有谁知道如何解决这个问题?
解决方法
如果使用cyanogenmod,setMobileDataEnabled(boolean)方法将在setMobileDataEnabled(String,boolean)…中更改,您可以看到
on this line of code.
所以你可以使用标准的方式,然后在NoSuchMethodException catch块中尝试这样的“cyanogenmod”方式:
Class[] cArg = new Class[2]; cArg[0] = String.class; cArg[1] = Boolean.TYPE; Method setMobileDataEnabledMethod; setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",cArg); Object[] pArg = new Object[2]; pArg[0] = getContext().getPackageName(); pArg[1] = true; setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager,pArg);
我不知道其他mods是否受到影响.