Android 代码控制手机数据网络的开关(5.0以上)

Android 代码控制手机数据网络的开关

android 5.0以前

Android 5.0以前使用ConnectivityManager通过反射两个方法setMobileDataEnabled和getMobileDataEnabled来控制移动网络开和关。

5.0以后

Android 5.0以后使用TelephonyMananger类通过反射获取setDataEnabled和getDataEnabled类完成操作。
注意:Manifest需要使用添加android:sharedUserId=”android.uid.system“,系统需要root或者应用需要系统签名

Code

添加权限

android.permission.MODIFY_PHONE_STATE 权限限制已经改为系统权限

<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>

//适应Android5.0+

    /**
     * 打开/关闭数据流量
     * @param enabled
     */
    public static void setDataEnabled(boolean enabled){
        TelephonyManager telephonyManager = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        try {
             Method method = telephonyManager.getClass().getDeclaredMethod("setDataEnabled",boolean.class);
             if (method != null){
                 method.invoke(telephonyManager,enabled);
             }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * true if mobile data is enabled
     * @return
     */
    public static boolean isDataEnabled(){
        TelephonyManager telephonyManager = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        try {
//            Method method = telephonyManager.getClass().getDeclaredMethod("isDataEnabled");
            Method method = telephonyManager.getClass().getDeclaredMethod("getDataEnabled");
            if (method != null){
              return (boolean) method.invoke(telephonyManager);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return false;
    }

Note:经过系统签名的app已经证明在android 5.0上可用

参考:Android 通过代码实现控制数据网络的开关(仅适用于5.0以上)

Android中使用代码控制Wifi及数据连接网络开关

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章