Android UsageStatsManager sample

Google has deprecated the function “getRecentTasks” of “ActivityManager” class. Now all it does is to get the list of apps that the current app has opened. But if you are writing app that “locks” access to specific apps with password or any other protection methods, you still need to be able to get top most activity/package to react accordingly to user changing current app and for example show your overlay.

Google introduces UsageStatsManager in api 21, which can replace “getRecentTasks” for new versions.

I’ve created sample project demonstrating how to use this api.

First of all you need to declare permission in AndroidManifest.xml



will disable warning that permission is system level and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.

So we need to check if our app was granted this permission

and if no, ask user to enable it

We are launching settings activity to allow app to get usage stats, its not android M default way to deal with permissions, we need to check result in onActivityResult

In this sample if user did not grant permission we will ask again while permission is not granted. In real application, its better to tell user why do we need this permission and turn off functionality if permission was not granted.

After the permission was eventually granted, we can query information about last active packages

There are a lot of methods in UsageStatsManager, that can be useful for your app. Checkout official documentation

Full source code for this article is available on GitHub

6 Replies to “Android UsageStatsManager sample”

  1. Thanks for your publication. I would also like to comment that the first thing you will need to perform is determine if you really need credit improvement. To do that you will need to get your hands on a copy of your credit profile. That should never be difficult, since the government mandates that you are allowed to have one no cost copy of your own credit report on a yearly basis. You just have to inquire the right persons. You can either look into the website for your Federal Trade Commission or even contact one of the leading credit agencies instantly.

Leave a Reply

Your email address will not be published. Required fields are marked *