Adding new uses-policies to existing device administrator on Android

夙愿已清 提交于 2019-12-05 21:32:36

AFAIK the only way is read your device-admin.xml from your apk, and you can do it in this way (from an Activity):

    PackageManager packageManager = getPackageManager();
    List <PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
    for (PackageInfo packageInfo : packageInfoList) {
        String publicSourceDir = packageInfo.applicationInfo.publicSourceDir;
        if (publicSourceDir.contains("your/app/path")) { // or equals, which you prefer
            File apkFile = new File(publicSourceDir);
            if (apkFile.exists()) {
                try {
                    JarFile jarFile = new JarFile(apkFile);
                    JarEntry jarEntry = jarFile.getJarEntry("xml/device-admin.xml");
                    InputStream is = jarFile.getInputStream(jarEntry);
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str;
                    while ((str = br.readLine()) != null) {
                        Log.d("entry: ", str); // your entries in the device-admin.xml
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            break;
        }
    }

To check if your active admin has granted policy, you can use https://developer.android.com/reference/android/app/admin/DevicePolicyManager#hasGrantedPolicy(android.content.ComponentName,%20int)

To verify uses policies from device-admin.xml I prefer to use https://developer.android.google.cn/reference/android/app/admin/DeviceAdminInfo.html?hl=zh-cn#usesPolicy(int) but when usesPolicy return true it doesn't mean that the active admin can use it.

ComponentName componentName = new ComponentName(context, MyDeviceAdminReceiver.class);
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.activityInfo = context.getPackageManager().getReceiverInfo(componentName, PackageManager.GET_META_DATA);
DeviceAdminInfo info = new DeviceAdminInfo(context, resolveInfo);

if (info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD)) {
    //your application declared <limit-password/> in device_admin.xml
}

DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (dpm.hasGrantedPolicy(componentName, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD)) {
    //active device admin has granted <limit-password/> policy
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!