如何在 Android 5.0 + 中获得 Top Activity

How to get Top Activity in Android 5.0 +

我正在使用下面的代码获取 Top Activity

private String getTopPackageName() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
    } else {
        final List<ActivityManager.RunningAppProcessInfo> pis = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo pi : pis) {
            if (pi.pkgList.length == 1) return pi.pkgList[0];
        }
    }
    return "";
}

它写在 API<21 但 API>=21 它 return"" :( 如何得到它? 我会尝试:

private void printForegroundTask() {
String currentApp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.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(TAG, "Current App in foreground is: " + currentApp);

}

但是 return 为空 :( 请帮助我!谢谢

getRunningTasks()API 级别 21(Lollipop)

中已弃用

作为替代,您可以这样做

List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
ComponentName componentInfo = task.get(0).importanceReasonComponent;
String packageName = componentInfo.getPackageName()

注:

this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here.

Refer the doc

更新:

    ActivityManager manager = (ActivityManager) MainActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
    ActivityManager.RunningAppProcessInfo runningAppProcessInfo = null;

    for(ActivityManager.RunningAppProcessInfo singleTask : task){
        if(singleTask.importanceReasonComponent !=null){
            runningAppProcessInfo = singleTask;
            break;
            }
    }

    if(runningAppProcessInfo!=null) {
        ComponentName componentInfo = runningAppProcessInfo.importanceReasonComponent;
        String packageName = componentInfo.getPackageName();
        Log.d("myPackageName", packageName);
    }

您也可以使用辅助功能服务,但为此您需要将用户重定向到辅助功能设置以将其打开。下面的示例代码用于获取刚刚打开的应用程序包,或者在您的情况下是顶部 activity.

  public class MyAccessibilityService extends AccessibilityService {

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
             String packageName = event.getPackageName();

        }
  }

您需要 "PACKAGE_USAGE_STATS" UsageStatsManager 的使用权限:

"This API requires the permission android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application."

参考:https://developer.android.com/reference/android/app/usage/UsageStatsManager.html