Alternative to getRunningTasks in Android L
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.
ActivityManager getRunningTasks not working on Lollipop?
Is this some breaking change?
Yes.
Is this documented somewhere?
Yes.
How to tell if application is in the background?
The most simple and straightforward solution that I found is the following:
public class AppStatusHelper {
private static final String TAG = AppStatusHelper.class.getSimpleName();
private static int mNumOfActivitiesInOnStarttoOnStopLifeCycle=0;
public static void onStart()
{
mNumOfActivitiesInOnStarttoOnStopLifeCycle++;
}
public static void onStop()
{
mNumOfActivitiesInOnStarttoOnStopLifeCycle--;
}
public static boolean isAppInBackground()
{
Log.d(TAG,"num->"+mNumOfActivitiesInOnStarttoOnStopLifeCycle+"\tisOnBackground->"+(mNumOfActivitiesInOnStarttoOnStopLifeCycle==0));
return mNumOfActivitiesInOnStarttoOnStopLifeCycle==0;
}
}
Just call onStart on every activity start and onStop on every activity stop. Then check if the counter is equal to 0.
Related Topics
Jelly Bean Datepickerdialog --- How to Cancel
Android Textwatcher.Aftertextchanged VS Textwatcher.Ontextchanged
Android: Activity Getting Destroyed After Calling Camera Intent
Creating an Android Trial Application That Expires After a Fixed Time Period
Android Studio Emulator Does Not Come with Play Store for API 23
Securityexception: Permission Denied (Missing Internet Permission)
What Are My Options for Storing Data When Using React Native? (iOS and Android)
Get Altitude by Longitude and Latitude in Android
How to Import Material Design Library to Android Studio
Android 5.0 Android:Elevation Works for View, But Not Button
Why My App Is Not Showing Up on Tablets in Google Play
Create Blurry Transparent Background Effect
How to Set Id of Dynamic Created Layout