尝试检索前台应用程序时出现Android 6.0棉花糖UsageStatsManager问题 [英] Android 6.0 Marshmallow UsageStatsManager issue when trying to retrieve foreground app

查看:234
本文介绍了尝试检索前台应用程序时出现Android 6.0棉花糖UsageStatsManager问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试查询UsageStatsManager的使用情况统计信息时,我都可以正确获取最近运行的应用程序.但是,如果我下拉状态栏并且有新的通知,则上次使用的应用程序(基于UsageStats)将更改为该通知的应用程序.结果,我收到有关前台应用程序已更改的错误警报.

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?

现在,我使用以下代码查询前台应用程序.该问题仅存在于棉花糖中(5.X正常工作).

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();
} 
}

推荐答案

您可以查询usageEvent,以检查上一个活动应用程序的事件是否为UsageEvents.Event.MOVE_TO_FOREGROUND.

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 ;
 }

这篇关于尝试检索前台应用程序时出现Android 6.0棉花糖UsageStatsManager问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆