码迷,mamicode.com
首页 > 移动开发 > 详细

Android L 5.0版本获取topActivity的方法

时间:2015-08-20 18:45:59      阅读:533      评论:0      收藏:0      [点我收藏+]

标签:

Android L版本中getRunningTasks已经失效

 

需要添加权限:

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

public static String getTopPkgName(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            Field field = null;
            try {
                field = RunningAppProcessInfo.class
                        .getDeclaredField("processState");
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            List<ActivityManager.RunningAppProcessInfo> processInfos = am
                    .getRunningAppProcesses();
            for (RunningAppProcessInfo app : processInfos) {
                if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        && app.importanceReasonCode == 0) {
                    Integer state = null;
                    try {
                        state = field.getInt(app);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    }
                    if (state != null && state == 2) {
                        if (app.pkgList.length > 0) {
                            Mlog.d(TAG, "---L getTopPkgName: " + app.pkgList[0]);
                            return app.pkgList[0];
                        }
                    }
                }
            }
        } else {
            List<RunningTaskInfo> runningTasks = am.getRunningTasks(1);
            if (runningTasks != null && runningTasks.size() > 0) {
                RunningTaskInfo runningTaskInfo = runningTasks.get(0);
                ComponentName topActivity = runningTaskInfo.topActivity;
                String packageName = topActivity.getPackageName();
                Mlog.d(TAG, "---getTopPkgName: " + packageName);
                return packageName;
            }
        }
        Mlog.d(TAG, "---getTopPkgName: NULL");
        return null;
    }

 参考:

http://stackoverflow.com/questions/24625936/getrunningtasks-doesnt-work-in-android-l

http://blog.csdn.net/wulianghuan/article/details/46348043

Android L 5.0版本获取topActivity的方法

标签:

原文地址:http://www.cnblogs.com/afluy/p/4745824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!