How to get Usage Access Permission programmatically

前端 未结 1 659
面向向阳花
面向向阳花 2020-12-09 19:42

My app needs to have Usage Access Permission in order to get information about the current running app on user\'s phone. I am able to successfully implement

相关标签:
1条回答
  • 2020-12-09 20:20

    You can simply give this Permission on the manifest, ignoring just this permission error:

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

    Than use Following code for permission

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isAccessGranted()) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
        }
    }
    
    
    private boolean isAccessGranted() {
            try {
                PackageManager packageManager = getPackageManager();
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
                AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                int mode = 0;
                if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.KITKAT) {
                    mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                            applicationInfo.uid, applicationInfo.packageName);
                }
                return (mode == AppOpsManager.MODE_ALLOWED);
    
            } catch (PackageManager.NameNotFoundException e) {
                return false;
            }
        }
    
    0 讨论(0)
提交回复
热议问题