How to get recent tasks on Android L?
To get the top (Foreground) package name currently running you need to use the Usage Stats API in Android Lollipop.
But notice user has to approve the access to usage data in the settings for each Application.
So you should prompt the user directly to the setting by launching setting action with
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
To get top packagename:
String topPackageName ;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
// Sort the stats by the last time used
if(stats != null) {
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
}
if(!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
See Android recent task executed by the user
Here is my solution:
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < recentTasks.size(); i++)
{
Log.d("Executed app", "Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+"");
}
Be careful!!The last ID is not the PID of the process!! If you want to get the PID of the process I used the following command :
mLogcatProc = Runtime.getRuntime().exec(new String[] {"ps"});
Read the result finding the application name and then split to obtain PID process.
How to get list of recent apps with Android API 21 Lollipop?
String topPackageName ;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
// Sort the stats by the last time used
if(stats != null) {
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
}
if(mySortedMap != null && !mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
Using the UsageStatsManager
, you can get the foreground package names currently running.
Source: How to get recent tasks on Android "L"?
Android: How can I get the current foreground activity (from a service)?
Is there a native android way to get a reference to the currently running Activity from a service?
You may not own the "currently running Activity".
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
- Send a broadcast
Intent
to the activity -- here is a sample project demonstrating this pattern - Have the activity supply a
PendingIntent
(e.g., viacreatePendingResult()
) that the service invokes - Have the activity register a callback or listener object with the service via
bindService()
, and have the service call an event method on that callback/listener object - Send an ordered broadcast
Intent
to the activity, with a low-priorityBroadcastReceiver
as backup (to raise aNotification
if the activity is not on-screen) -- here is a blog post with more on this pattern
How to bring most recently used third party Activity to front?
Figured it out by looking at the Android source code - this is exactly what the Recent Tasks screen does, both pre- and post-Honeycomb:
RecentTaskInfo recentTask = recentTasks.get(1); // task 0 is current task
// maintains state more accurately - only available in API 11+ (3.0/Honeycomb+)
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.moveTaskToFront(recentTask.id, ActivityManager.MOVE_TASK_WITH_HOME);
} else { // API 10 and below (Gingerbread on down)
Intent restartTaskIntent = new Intent(recentTask.baseIntent);
if (restartTaskIntent != null) {
restartTaskIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
try {
startActivity(restartTaskIntent);
} catch (ActivityNotFoundException e) {
Log.w("MyApp", "Unable to launch recent task", e);
}
}
}
Permission android.permission.REORDER_TASKS is necessary for this to work correctly.
Related Topics
Alert Dialog from Android Service
Noclassdeffounderror When Googleanalyticstracker.Getinstance()
Java.Lang.Noclassdeffounderror: Javax.Activation.Datahandler in Android
How to Split Comma-Separated Value in SQLite
Making Data Persistent in Android
Fragment Onresume() & Onpause() Is Not Called on Backstack
Showing Empty View When Listview Is Empty
Android Studio How to Package Single Aar from Multiple Library Projects
Firebase (Fcm) How to Get Token
Does Android Keep the .Apk Files? If So Where
Difference Between Activity and Fragmentactivity
Listing All Extras of an Intent
Fade in Fade Out Android Animation in Java
Navigation Drawer: How to Set the Selected Item at Startup