Android 6.0 Marshmallow UsageStatsManager issue when trying to retrieve foreground app

纵饮孤独 提交于 2019-11-28 02:49:12

问题


whenever I try to query the Usage Stats of the UsageStatsManager I can correctly get the last running app. However, if I pull down the status bar and there is a new notification, the last used app (based on UsageStats) will change to that of the notification. As a result, I get false alarms that the foreground application has changed.

I can't seem to find a way to filter those specific draws. Any ideas?

Right now, I query for the foreground app with the following code. The problem exists only in Marshmallow (5.X works correctly).

UsageStatsManager mUsageStatsManager = (UsageStatsManager) rotationManager.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 * 2, 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()) {
    foregroundApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
} 
}

回答1:


You can query the usageEvent to check if the last active app's event is UsageEvents.Event.MOVE_TO_FOREGROUND.

After you get the foregroundApp, you can refer to the following code:

 UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 100 * 1000, time);
 UsageEvents.Event event = new UsageEvents.Event();
 // get last event
 while (usageEvent.hasNextEvent()) {
     usageEvent.getNextEvent(event);
 }
 if (foregroundApp.equals(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
     return foregroundApp ;
 }



回答2:


In android 6.0 os, getUsageStats function giving list size zero. For confirmation, you can check any lock app from play store. Those app are not working in android 6.0.




回答3:


Take a look at https://github.com/ricvalerio/foregroundappchecker, it might be what you need. Provides sample code, and takes away the pain of having to implement cross version foreground detector.



来源:https://stackoverflow.com/questions/33307042/android-6-0-marshmallow-usagestatsmanager-issue-when-trying-to-retrieve-foregrou

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