How to Get the Time spent on an application in Android Programmatically

前端 未结 3 919
借酒劲吻你
借酒劲吻你 2020-12-01 04:39

I want to get the Usage time of all those applications which i have used today.

As i am getting the those details by dialing *#*#4636#*#*. But i want t

3条回答
  •  Happy的楠姐
    2020-12-01 05:14

    TLDR if you used @chand_becse code and your list is empty just add this reguestPermissions method and call this in your onCreate method(right after UsageStatsManager is initialized)

    Chand becse answer is completely valid, though you have to bear in mind that your application needs permission to use stats from other apps. Because permision.PACKAGE_USAGE is something that you can't just simply ask user for, you have to redirect him to ACTION_USAGE_ACCESS_SETTINGS view and let him turn on those permissions manually. I've also noticed that every time I'm getting -1 when I check if my application already got permissions(even if it has already obtained them), so I'm checking if the stats list is empty. If it is I assume my application needs permissions for this functionality.

        private void requestPermissions() {
            List stats = mUsageStatsManager
                    .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
            boolean isEmpty = stats.isEmpty();
            if (isEmpty) {
                startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
            }
        }
    
    

提交回复
热议问题