In Android 6.0 Marshmallow I query for the foreground app with the following code but there was a problem with incoming notifications because it shows foreground app to the app which sends notification. The problem exists only in Marshmallow (5.X works correctly).
// 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;
}
and then notification problem is solved using solution from this answer UsageEvents.
As solution in answer I put the code and its working to get Foreground app but it delayed by 3 seconds. My service is checking foreground app and is repeating every 500ms but whatsapp package detects after 3 seconds of starting whatsapp. this is code of UsageEvents i use from above solution.
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;
}
}