9
在Android 6.0 Marshmallow我使用以下代碼查詢前臺應用程序,但傳入的通知有問題,因爲它向發送通知的應用程序顯示前臺應用程序。問題只存在於棉花糖(5.X正常工作)。在棉花糖中獲取前臺應用程序的packageName延遲3秒
// 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;
}
然後通知問題解決使用從這個答案UsageEvents解決方案。
作爲答案的解決方案,我把代碼和它的工作得到前臺應用程序,但它延遲了3秒。我的服務正在檢查前臺應用程序,並且每500ms重複一次,但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;
}
}