15

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 it using the following code with the help from the following link.

Usage Access apps

Here is my working code

public void showDialog()
 {
     if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

         @SuppressWarnings("WrongConstant")
         UsageStatsManager usm = (UsageStatsManager) getSystemService("usagestats");
         long time = System.currentTimeMillis();
         List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
                 time - 1000 * 1000, time);
         if (appList.size()==0)
         {
             AlertDialog alertDialog = new AlertDialog.Builder(this)
                     .setTitle("Usage Access")
                     .setMessage("App will not run without usage access permissions.")
                     .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                         @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                         public void onClick(DialogInterface dialog, int which) {
                             // continue with delete
                             Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                            // intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$SecuritySettingsActivity"));
                             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                             startActivityForResult(intent,0);
                         }
                     })
                     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             // do nothing
                             dialog.dismiss();
                         }
                     })
                     .setIcon(android.R.drawable.ic_dialog_alert)
                     .create();

             alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
             alertDialog.show();
         }                      else {
             Intent intent = new Intent(this, PackageService.class);
             startService(intent);
             finish();
         }
     }else
     {
         Intent intent = new Intent(this, PackageService.class);
         startService(intent);
         finish();
     }
 }

This code will show a user an alert dialog that Usage Access permission is required and will take user to the settings screen from where it can be enabled.

Everything works perfectly with this. Only thing that I want is that how to give my app usage access permission by default without showing any dialog to user until he/she doesn't turn it off manually?

7
  • have you found any solution for that please?? Jan 12, 2017 at 12:20
  • @vivek, once its turned on, how were you detecting the current app being opened in user's phone..? I mean the PackageService details Feb 14, 2018 at 13:07
  • @Anukoolsrivastav can you describe more what you want to ask ? Feb 14, 2018 at 13:35
  • @VivekMishra I want to write a service that will detect whenever any other app is opened/foreground in phone. Feb 14, 2018 at 13:38
  • what will be the PackageService.class? Jun 19, 2018 at 10:08

1 Answer 1

29

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;
        }
    }
3
  • @samchaudhari with the given method, the user still has to open the Usage access page and turn it on manually. Does it turn it on automatically for you? without any user input?
    – kash
    Aug 7, 2017 at 3:10
  • @kash there is not any way to turn it on automatically. user must turn it on manually. Aug 8, 2017 at 10:14
  • how we add tutorial screen in usage setting screen Jan 23, 2019 at 20:42

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.