private void setMobileDataEnabled(Context context,boolean enabled) throws ClassNotFoundException,NoSuchFieldException,IllegalAccessException,NoSuchMethodException,InvocationTargetException { final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final Class conmanClass = Class.forName(conman.getClass().getName()); final Field connectivityManagerField = conmanClass.getDeclaredField("mService"); connectivityManagerField.setAccessible(true); final Object connectivityManager = connectivityManagerField.get(conman); final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled",Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(connectivityManager,enabled); }
03-30 12:42:29.466: W/System.err(5966):
java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] 03-30
12:42:29.466: W/System.err(5966): at
java.lang.Class.getMethod(Class.java:664) 03-30 12:42:29.466:
W/System.err(5966): at
java.lang.Class.getDeclaredMethod(Class.java:626)
java.lang.NoSuchMethodException:setMobileDataEnabled [boolean] @在line下面.
final Method setMobileDataEnabledMethod =
connectivityManagerClass.getDeclaredMethod(“setMobileDataEnabled”,
Boolean.TYPE);
解决方法
It seems like the setMobileDataEnabled method no longer exists in
ConnectivityManager and this functionality was moved to
TelephonyManager with two methods getDataEnabled and setDataEnabled.
public void setMobileDataState(boolean mobileDataEnabled) { try { TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled",boolean.class); if (null != setMobileDataEnabledMethod) { setMobileDataEnabledMethod.invoke(telephonyService,mobileDataEnabled); } } catch (Exception ex) { Log.e(TAG,"Error setting mobile data state",ex); } } public boolean getMobileDataState() { try { TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled"); if (null != getMobileDataEnabledMethod) { boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService); return mobileDataEnabled; } } catch (Exception ex) { Log.e(TAG,"Error getting mobile data state",ex); } return false; }
执行代码时,您会收到SecurityException,指出用户10089和当前进程都没有android.permission.MODIFY_PHONE_STATE.
应添加权限MODIFY_PHONE_STATE
我从Answer得到了这个谢谢Muzikant
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。