Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of recent apps with Android API 21 Lollipop?

I'm creating a home launcher and I want to have a compatibility with the Android 5.0, Lollipop. I want to get a list of recent apps on the launcher.

But since ActivityManager.getRecentTasks() no longer works in API 21, how can I do this ?

like image 664
rosghub Avatar asked Dec 04 '14 00:12

rosghub


1 Answers

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"?

like image 180
An SO User Avatar answered Sep 22 '22 17:09

An SO User