Won*_*res 9 android package foreground usagestatsmanager android-6.0-marshmallow
在Android 6.0 Marshmallow中,我使用以下代码查询前台应用程序但是传入通知存在问题,因为它向发送通知的应用程序显示了前台应用程序.问题仅存在于Marshmallow中(5.X正常工作).
// API 21 and above
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static String getProcessNew(UsageStatsManager mUsageStatsManager, Context c) throws Exception {
String st = null;
try {
long endTime = System.currentTimeMillis();
long beginTime = endTime - 1000 * 10;
// We get usage stats for the last minute
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginTime,
endTime);
// 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()) {
st = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} catch (Exception e) {
Log.d("main", "Wxxxxexx " + e);
}
return st;
}
Run Code Online (Sandbox Code Playgroud)
然后使用此答案UsageEvents中的解决方案解决通知问题.
作为答案中的解决方案,我将代码及其工作用于获取Foreground应用程序,但它延迟了3秒.我的服务是检查前台应用程序,并且每隔500毫秒重复一次,但whatsapp程序包在启动whatsapp 3秒后检测到.这是我在上面的解决方案中使用的UsageEvents的代码.
if (BuildV >= 23) {
long endTime = System.currentTimeMillis();
long beginTime = endTime - 1000 * 10;
UsageEvents usageEvents = mUsageStatsManager.queryEvents(beginTime, endTime);
UsageEvents.Event event = new UsageEvents.Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
}
if (st.equals(event.getPackageName())
&& event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
pack = st;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |