Search code examples
androidandroid-5.0-lollipop

Alternative to getRunningTasks in Android L


It's been well documented that getRunningTasks is now deprecated in Android L. I used this to get top activity and this was an important feature of my app. Though not complete, a new solution in Android L has been promised by a Google Employee. The solution states:

"for L we do plan to have a new solution that will address some of the existing use cases of getRecentTasks(): we hope to expose the system’s internal usage stats service in a new and expanded form that is available to third party apps through the SDK.

The new usage stats service should have two major pieces of information. First, it will provided aggregated stats of the time the user spent in each app, and the last launch time of those apps, rolled up over days, weeks, months, and years. Second, it will include detailed usage events over the last few days, describing the time and ComponentName when any activity transitions to the foreground or background.

Access to this new usage data will require that the user explicitly grant the app access to usage stats through a new settings UI. They will be able to see all apps that have access and revoke access at any point.

I realize that this won’t cover every possible use of the old getRecentsTask API, and I apologize for that. However, for what we see to be the key current uses of the API, a new usage stats API should be much more robust and efficient."

You can read more about it here: https://code.google.com/p/android-developer-preview/issues/detail?id=29#c50

I have tried looking in the Android L documentation but cannot find anything that talks the usage stats service mentioned above. Has anyone used this API? Can anyone point me to the documentation for this?


Solution

  • The system statistics api evoked in your question is also presented here and the detailed API is here. As far as I can see this API won't allow you to get the current top activity.

    i.e. you have the ability to receive UsageEvent with the type MOVE_TO_FOREGROUND by using UsageStatsManager.queryEvents but according javadoc :

    The last few minutes of the event log will be truncated to prevent abuse by applications.

    So it is really an API to get statistics, not to get realtime information. (note that the now deprecated getRunningTasks() was neither intended to retrieve realtime data : javadoc)

    On the other hand, if you are only interested in top activity of your own app: you can use getAppTasks() returning a List<AppTask> where you can get the RecentTaskInfo with getTaskInfo


    EDIT : another approach is provided here.

    It is based on UsageStats and UsageStats.getLastTimeUsed(). Drawback : it requires additional permission and gives you only the package name -not the activity-, but it gives you real time data.