如何以编程方式在Android中启用/禁用背景数据?

时间:2018-03-14 03:00:23

标签: android networking

在Android O中以编程方式启用和禁用Android设备中的背景数据值得分享,因为我在搜索时找不到解决方案。谢谢。

1 个答案:

答案 0 :(得分:-1)

包含在清单中所需的许可是;

<uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY" tools:ignore="ProtectedPermissions"/>

权限是系统权限,因此应用程序应该是系统应用程序(由相关的OEM密钥签名)。

private static final int THREAD_WAIT_TIMEOUT_IN_MS = 100;

private boolean restrictBackgroundData(boolean enable, int timeout) {
    Boolean result = false;
    try {
        final ConnectivityManager connectivityManager = (ConnectivityManager) getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());

        final Method getNetworkPolicyManager = connectivityManagerClass.getDeclaredMethod(
                "getNetworkPolicyManager");
        getNetworkPolicyManager.setAccessible(true);

        final Object iNetworkPolicyManager = getNetworkPolicyManager.invoke(connectivityManager);
        final Class iNetworkPolicyManagerClass = Class.forName(iNetworkPolicyManager.getClass()
                .getName());
        final Method setRestrictBackground = iNetworkPolicyManagerClass.getDeclaredMethod("setRestrictBackground",
                boolean.class);
        final Method getRestrictBackground = iNetworkPolicyManagerClass.getDeclaredMethod("getRestrictBackground");
        setRestrictBackground.setAccessible(true);
        getRestrictBackground.setAccessible(true);
        // Check if the state is already set
        result = (Boolean) getRestrictBackground.invoke(iNetworkPolicyManager);
        result = ((result && enable) || ((!result) && (!enable)));

        if (!result) {
            // Set state
            setRestrictBackground.invoke(iNetworkPolicyManager, enable);

            while (timeout > 0) {
                // Check if the state is set
                result = (Boolean) getRestrictBackground.invoke(iNetworkPolicyManager);
                result = ((result && enable) || ((!result) && (!enable)));
                if (result) {
                    break;
                }
                try {
                    Thread.sleep(THREAD_WAIT_TIMEOUT_IN_MS);
                } catch (InterruptedException e) {
                }
                timeout -= THREAD_WAIT_TIMEOUT_IN_MS;
            }
        }
    } catch (Exception e) {
    }
    return result;
}

在Android O设备上经过测试和验证。