android 判断当前应用是否处于桌面

一般桌面的应用会在主activity中添加属性:"android.intent.category.Home",所以先判断属于桌面的应用,桌面应用的判断5.0之前和之后有所不同,下面分别进行说明

一.android5.0之前

1.判断当前界面,就是需要判断当前的RunningTasks中的第一个应用

1).通过ActivityManager获取RunningTasks

2).取出RunningTasks中的topActivity的PackageName

3).和RunningTasks中得到的List做比较

4).demo

 public static boolean isHome(Context context) {
        return getLauncherPackagenames(context).contains(getTopApp(context));
    }


    private static List<String> getLauncherPackagenames(Context context) {
        List<String> names = new ArrayList<String>();
        PackageManager manager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> list = manager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo info : list) {
            names.add(info.activityInfo.packageName);
        }
        return names;
    }


    public static String getTopApp(Context context) {
        //android5.0 below
        ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        return rti.get(0).topActivity.getPackageName();
    }

注意:需要加入如下权限:

<uses-permission android:name="android.permission.GET_TASKS"/>

二.android5.0之后

android5.0之后之前的方法失效,但是新引进了类UsageStatsManager,可以进行相关的判断

1.UsageStatsManager介绍


UsageStatsManager

public final class UsageStatsManager
extends Object
java.lang.Object
   ↳ 	android.app.usage.UsageStatsManage
 PAST                   REQUEST_TIME                    TODAY                   FUTURE
 ————————————————————————————||———————————————————————————¦-----------------------|
                        YEAR ||                           ¦                       |
 ————————————————————————————||———————————————————————————¦-----------------------|
  MONTH            |         ||                MONTH      ¦                       |
 ——————————————————|—————————||———————————————————————————¦-----------------------|
   |      WEEK     |     WEEK||    |     WEEK     |     WE¦EK     |      WEEK     |
 ————————————————————————————||———————————————————|———————¦-----------------------|
                             ||           |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
 ————————————————————————————||———————————————————————————¦-----------------------|
 

提供设备使用的历史记录和统计,数据汇总的时间间隔为:天,周,月和年.

2.UsageStatsManager的queryUsageStats方法,获取给定时间范围的应用程序使用情况统计信息,按指定的时间间隔汇总

public List<UsageStats> queryUsageStats (int intervalType, 
                long beginTime, 
                long endTime)

3.兼容5.0以下版本的demo

 public static boolean isHome(Context context) {
        return getLauncherPackagenames(context).contains(getTopApp(context));
    }


    private static List<String> getLauncherPackagenames(Context context) {
        List<String> names = new ArrayList<String>();
        PackageManager manager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> list = manager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo info : list) {
            names.add(info.activityInfo.packageName);
        }
        return names;
    }

    private static String getTaskTopPackage(Context context) {

        final ActivityManager am = (ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : list) {
            if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && info.processState == ActivityManager.START_TASK_TO_FRONT) {
                return info.processName;
            }
        }
        return null;
    }


    public static String getTopApp(Context context) {
        //android5.0 above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager m = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            if (null!=m){
                long now = System.currentTimeMillis();
                //obtain recent in 1 hour app status
                List<UsageStats> stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 60 * 1000 * 60, now);
                Log.d(TAG,"getTopApp app packagename: "+stats.size());
                String topActivity = "";
                //obtain recent run app,maybe running app
                if ((stats != null) && (!stats.isEmpty())) {
                    int j = 0;
                    for (int i = 0; i < stats.size(); i++) {
                        if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                            j = i;
                        }
                    }
                    topActivity = stats.get(j).getPackageName();
                }
                Log.d(TAG,"getTopApp app packagename: "+topActivity);
                return topActivity;
            }
        }else {
            //android5.0 below
            ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
            return rti.get(0).topActivity.getPackageName();
        }
        return null;
    }

注意:需要加入如下权限:

 <uses-permission android:name="android.permission.GET_TASKS"/>
 <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值