Android UsageStatsManager: Get a list of currently running apps on phone

后端 未结 1 456
天涯浪人
天涯浪人 2021-01-06 17:07

I am trying to get a list of currently running apps on my phone. Here is the code I am using:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VER         


        
相关标签:
1条回答
  • 2021-01-06 18:02

    The problem is that your application does not have the system permission of android:get_usage_stats.

    You can use the below code to check if you have the permission:

    public static boolean needPermissionForBlocking(Context context){
    try {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
        return  (mode != AppOpsManager.MODE_ALLOWED);
    } catch (PackageManager.NameNotFoundException e) {
        return true;
    }
    }
    

    If you do not have the permission then the user must enable this permission by going to Settings -> Security-> Apps with usage access, and then adding your application. Your code should then work fine.

    0 讨论(0)
提交回复
热议问题