Android 6.0 Marshmallow UsageStatsManager issue when trying to retrieve foreground app

百般思念 提交于 2019-11-29 09:08:58

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

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.

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.

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