简体   繁体   中英

Android: get running time of installed apps

How we show all installed application with running time and get last usage of applications and show it? I get all installed application and show it, but i want to show running time of applications also.

Try this:

Add this in manifest file:

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

You also need to take package usage stats permission at runtime

Use this function to check for the Usage Stats permission:

@TargetApi(Build.VERSION_CODES.M)
public static boolean hasUsageStatsPermission(Context context) {
    boolean granted = false;
    AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
    if (mode == AppOpsManager.MODE_DEFAULT)
        granted = (context.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
    else
        granted = (mode == AppOpsManager.MODE_ALLOWED);
    return granted;
}

If you don't have the permission, use this code to take the user to your app's permission page:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).setData(Uri.parse("package:" + "your package name")))

Now the actual part where you fetch the last usage time of all installed apps:

PackageManager packageManager = getPackageManager();
List<ApplicationInfo> applicationInfoList = packageManager.getInstalledApplications(0);
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
long start = calendar.getTimeInMillis();
long end = System.currentTimeMillis();
stats = usageStatsManager.queryAndAggregateUsageStats(start, end);

for (ApplicationInfo info : applicationInfoList) {
            GetAppInfo(info);
        }

Now the GetAppInfo function:

UsageStats usageStats = stats.get(info.packageName);
long lastTimeUsed;
long actualLastTimeUsed;
  if(usageStats!=null){
     lastTimeUsed = usageStats.getLastTimeUsed();
      actualLastTimeUsed = currentTime - lastTimeUsed;
  }

As you can see it's a long process to get just the last usage time of all installed apps.

Note: Remember to do all this in background/worker thread rather than the UI or main thread or else it might freeze the ui

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM