# 附件
# 流量控制附件
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";
// 禁止流量数据访问
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();
}
/**
* 查询应用流量是否被禁用
*
* @param packageName 包名
* @return true:被禁用 false:没有被禁用
*/
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;
}
}