我目前正在开发AppLocker应用程序,它可以检测用户使用UsageStatsManager打开的应用程序。我使用后台服务BackgroundServices.java进行检测。但是,当我们通过向下滚动打开通知栏时,UsageStatsManager会随机地将任何通知视为正在运行,并且不必要地打开LockScreen。
用于检测和返回当前使用的应用程序BackgroundServices.java的主块
private String printForegroundTask() {
String currentApp = "NULL";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
// Log.e("AppLockerService", "Current App in foreground is: " + currentApp)
return currentApp;
}发布于 2020-05-07 22:05:16
所以我发布这篇文章来分享上面问题的答案。我在整个互联网上搜索了很多,发现了这个。
我要感谢Muthukrishnan Rajendran回答这个问题。His Profile Link
我希望那些正在寻找与这个问题相关的答案的人可以通过这个链接轻松地解决它。谢谢
https://stackoverflow.com/questions/61643051
复制相似问题