Android7如何获取当前运行的Activity的包名

获取TopApp

private String getTopApp() {
        String topActivity = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUsageStatsManager != null) {
                long now = System.currentTimeMillis();
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
                List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, calendar.getTimeInMillis(), now);
                Log.i(TAG, "Running app number in last 1 day : " + stats.size());
                //取得最近运行的一个app,即当前运行的app
                if ((stats != null) && (!stats.isEmpty())) {
                    Collections.sort(stats, LAST_TIME_COMPARATOR);
                    int size = stats.size();
                    topActivity = stats.get(size - 1).getPackageName();
                    for (UsageStats stats1 : stats) {
                        Log.i(TAG, "stats1=" + stats1
                                + "  time=" + stats1.getLastTimeUsed()
                                + " packageName=" + stats1.getPackageName());
                    }
                }
                Log.i(TAG, "top running app is : " + topActivity);
            }
        } else {
            ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
            List.RunningTaskInfo> forGroundActivity = activityManager.getRunningTasks(1);
            ActivityManager.RunningTaskInfo currentActivity;
            currentActivity = forGroundActivity.get(0);
            topActivity = currentActivity.topActivity.getPackageName();
        }
        return topActivity;
    }

排序

    public final Comparator LAST_TIME_COMPARATOR = new Comparator() {
        @Override
        public int compare(UsageStats lhs, UsageStats rhs) {
            return Long.compare(lhs.getLastTimeUsed(), rhs.getLastTimeUsed());
        }
    };

声明权限

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions"
        />

注意AndroidManifest.xml的头

"http://schemas.android.com/apk/res/android"
    package="xxxx"
    xmlns:tools="http://schemas.android.com/tools"
    >

加了tools哦

总结

到了Android6.0版本,即Marshmallow(api level 23)时,获取TopApp的方法改变了。

你可能感兴趣的:(Android)