Get (real) foreground process using activityManager.getRunningAppProcesses()

…衆ロ難τιáo~ 提交于 2019-12-03 10:56:59
Jared Rummler

What is the correct method to get current foreground process and prevent false positives?

UsageStatsManager is the only official API to get the current running app (see #50).

Using getRunningTasks(int maxNum), getRunningAppProcesses() or AccessibilityService to get the foreground app has never been reliable. The documentation for the first two methods has the following warning: Note: this method is only intended for debugging


Below is an example for getting the top app using UsageStatsManager:

Calendar endCal = Calendar.getInstance();
Calendar beginCal = Calendar.getInstance();
beginCal.add(Calendar.MINUTE, -30);
UsageStatsManager manager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> stats =  manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  
    beginCal.getTimeInMillis(), endCal.getTimeInMillis());
Collections.sort(stats, new Comparator<UsageStats>() {

  @Override public int compare(UsageStats lhs, UsageStats rhs) {
    long time1 = lhs.getLastTimeUsed();
    long time2 = rhs.getLastTimeUsed();
    if (time1 > time2) {
      return -1;
    } else if (time1 < time2) {
      return 1;
    }
    return 0;
  }
});
// The first "UsageStats" in the list will be the top application.
// If the list is empty you will need to ask for permissions to use UsageStatsManager
// To request permission:
// startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

I know this isn't the answer you are hoping for. Apps like CM Security and AppLock use UsageStatsManager on Android 5.1.1+. Due to SeLinux, it is impossible to get the foreground app using getRunningTasks(int maxNum) or getRunningAppProcesses().

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