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及數據連接網絡開關

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