如何在android Lollipop和marshmallow中获取当前打开的应用程序包名称

时间:2016-05-10 12:09:59

标签: android android-recents

我正在尝试获取当前打开的应用程序包名称,我得到了kitkat,但它将无法在android lollipop中运行,它每次都会返回我的安装应用程序包名称,我不知道为什么会发生这种情况,代码

private void getAppInfoLowerLolipop(Context aContext) {
    ActivityManager am = (ActivityManager) aContext
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> alltasks = am.getRunningTasks(1);

    for (ActivityManager.RunningTaskInfo aTask : alltasks) {
        System.out.println("==== Not Package Name : "
                + aTask.topActivity.getPackageName().toString());
    }
}

和Android棒棒糖和棉花糖

private void getAppInfoForLolipop(Context context) {

    try {
        ActivityManager.RunningAppProcessInfo.class
                .getDeclaredField("processState");
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appList = am
                .getRunningAppProcesses();

        System.out.println("==== Lolipop Package Name : "
                + appList.get(0).processName.toString());
    } catch (Exception ignored) {
        System.out.println("==== Error Lolipop : " + ignored);
    }

}

在清单文件中,我允许获取最近的任务

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

0 个答案:

没有答案