# Attachment

# Traffic Control Accessories

NetworkPolicyForApp.java

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;

public class NetworkPolicyForApp {

    private static final String TAG = "XTCNetworkPolicy";
    // Prohibit traffic data access
    public static final int RULE_REJECT_METERED = 1 << 2;

    private Object mPolicyMgr;
    private PackageManager mPackageMgr;

    public NetworkPolicyForApp(Context context) {
        try {
            mPolicyMgr = Class.forName("android.net.NetworkPolicyManager")
                    .getDeclaredMethod("from", Context.class).invoke(null, context);
        } catch (ClassNotFoundException | NoSuchMethodException |
                InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        mPackageMgr = context.getPackageManager();
    }

    /**
     * Query whether traffic is disabled
     *
     * @param packageName 
     * @return true:Banned false:Not banned
     */
    public boolean isMobileTrafficDisabled(String packageName) {
        return isRuleEnabled(packageName, RULE_REJECT_METERED);
    }

    private boolean isRuleEnabled(String packageName, int rule) {
        int uid = getUid(packageName);
        if (uid <= 1000) {
            Log.e(TAG, "invalid uid:" + uid);
            return false;
        }
        try {
            Object policy = mPolicyMgr.getClass()
                    .getDeclaredMethod("getUidPolicy", int.class).invoke(mPolicyMgr, uid);
            int origin = (int) policy;
            if ((origin & rule) != 0) {
                return true;
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return false;
    }

    private int getUid(String packageName) {
        try {
            ApplicationInfo info = mPackageMgr.getApplicationInfo(packageName,
                    PackageManager.GET_META_DATA);
            return info.uid;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "error get uid for package name:" + packageName);
        return -1;
    }
}
Last Updated: 9/23/2019, 9:03:12 AM