Android移动数据开关开启关闭方法

本文奉上一个Android移动数据开关开启关闭方法,闲话少说,直接上代码。

public static void setDataEnabled(int slotIdx, boolean enable,Context context) throws Exception
{
    try {
        int subid = SubscriptionManager.from(context).getActiveSubscriptionInfoForSimSlotIndex(slotIdx).getSubscriptionId();
        TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled", int.class, boolean.class);
        if (null != setDataEnabled) {
            setDataEnabled.invoke(telephonyService, subid, enable);
            LogUtil.LOGD(TAG,"setDataEnabled suc",false);
        }
    }catch (Exception e)
    {
        e.printStackTrace();
        LogUtil.LOGD(TAG,"setDataEnabled exception",false);
    }
}

public static boolean getDataEnabled(int slotIdx,Context context) throws Exception
{
    boolean enabled = false;
    try {
        int subid = SubscriptionManager.from(context).getActiveSubscriptionInfoForSimSlotIndex(slotIdx).getSubscriptionId();
        TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        Method getDataEnabled = telephonyService.getClass().getDeclaredMethod("getDataEnabled", int.class);
        if (null != getDataEnabled) {
            enabled =  (Boolean) getDataEnabled.invoke(telephonyService, subid);
        }
    }catch (Exception e)
    {
        e.printStackTrace();
    }

    return enabled;
}

另外,控制移动数据开关需要一个系统权限

<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"></uses-permission>
获取这个系统权限需要app为系统应用,把app放在/system/priv-app或者对app进行系统签名均可获得系统权限。

猜你喜欢

转载自blog.csdn.net/baidu_27196493/article/details/79664183
今日推荐