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

末鹿安然 提交于 2019-12-18 04:19:19

问题


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 ?


回答1:


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




回答2:


I was troubled with whis, since android has deprecated some api such as getRecentTasks,getRunningTasks above API21, they say these method is no longer available to third party app. When i call these api on the device above lollipop, it just return null or my app :(.

Then i found a method to instead of these api, as long as we can get the app'spackagename, we can do almost anything we want. Android based on linux, i found this AndroidProcesses.It can use /proc to get android's application pid and processName, and the processName is such ad com.xxx.xxx:remote. Notice that the front of : is the packageName :)

After get the packageName, i think you know what to do. I think we can start a Service to statistics the most recent used app according to the process running background. The longer the statistical time, the more accurate the results.



来源:https://stackoverflow.com/questions/27284205/how-to-get-list-of-recent-apps-with-android-api-21-lollipop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!