• Android L 5.0版本获取topActivity的方法


    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

  • 相关阅读:
    OFDM系统中频域同步技术及FPGA实现
    SystemVerilog的挑战和机遇
    基础知识要牢固..复习复习,再复习
    样式在.net下测试不成功.附解决办法
    学习.net2.0的网站
    08年又快结束了..抱怨下!~
    今天去面试.net开发,感想
    在b/s开发中经常用到的javaScript技术
    淘宝"新版"首页
    Ajax技术简单入门
  • 原文地址:https://www.cnblogs.com/afluy/p/4745824.html
Copyright © 2020-2023  润新知