微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Android 4.4.2上以编程方式切换手机数据

我一直使用这段代码通过编程方式启用移动数据:
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是否受到影响.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐