Trong truy vấn Android 6.0 Marshmallow I cho ứng dụng nền trước với mã sau nhưng đã xảy ra sự cố với thông báo đến vì nó hiển thị ứng dụng tiền cảnh cho ứng dụng gửi thông báo. Vấn đề tồn tại chỉ trong Marshmallow (5.X hoạt động chính xác).Lấy gói ứng dụng tiền cảnhName trong Marshmallow bị trễ 3 giây
// 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;
}
và sau đó giải quyết sự cố bằng giải pháp từ câu trả lời này UsageEvents.
Như giải pháp trong câu trả lời tôi đặt mã và làm việc của nó để có được ứng dụng Foreground nhưng nó bị trì hoãn 3 giây. Dịch vụ của tôi đang kiểm tra ứng dụng tiền cảnh và lặp lại mỗi 500ms nhưng gói whatsapp phát hiện sau 3 giây bắt đầu WhatsApp. đây là mã của UsageEvents tôi sử dụng từ giải pháp trên.
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;
}
}