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

Posted 邱小琪Yogi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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<UsageStats> 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<ActivityManager.RunningTaskInfo> forGroundActivity = activityManager.getRunningTasks(1);
            ActivityManager.RunningTaskInfo currentActivity;
            currentActivity = forGroundActivity.get(0);
            topActivity = currentActivity.topActivity.getPackageName();
        
        return topActivity;
    

排序

    public final Comparator<UsageStats> LAST_TIME_COMPARATOR = new Comparator<UsageStats>() 
        @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的头

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

加了tools哦

总结

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

以上是关于Android7如何获取当前运行的Activity的包名的主要内容,如果未能解决你的问题,请参考以下文章

如何获取系统当前运行的activity对象

android 如何获取手机当前的Activity实例

解决:Android 8.0检测不到当前的activity

获取当前栈顶的Activity

android中service显示dialog

怎样获取安卓系统自带的package和activity