1

我试图获取用户在会话中打开的所有应用程序的名称(会话以解锁手机开始,以关闭屏幕结束)。

首先,我尝试将当前应用程序置于前台。我在后台使用服务并尝试了不同的代码:

AndroidManifest.xml:

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

TaskListenerService.java:

        ActivityManager am = (ActivityManager) TaskListenerService.this.getSystemService(ACTIVITY_SERVICE);
    ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
    String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
    Toast.makeText(this, "name foregroundTaskInfo: " + foregroundTaskPackageName, Toast.LENGTH_SHORT).show();


    PackageManager pm = TaskListenerService.this.getPackageManager();
    PackageInfo foregroundAppPackageInfo = null;
    try {
        foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
        String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
        Toast.makeText(this, "name foregroundTaskAppName: " + foregroundTaskAppName, Toast.LENGTH_SHORT).show();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

它在我自己的应用程序中运行良好,但如果另一个应用程序在前台,我将作为包获得“com.sec.android.app.launcher”(“TouchWiz-Start”作为foregroundTaskAppName)。我还在 TaskListenerService.java 中尝试了这段代码,结果相同:

   ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> taskInfo = am.getRunningAppProcesses();

    for (ActivityManager.RunningAppProcessInfo task:taskInfo) {
        if (task.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
            Toast.makeText(this, "name: " + task.processName, Toast.LENGTH_SHORT).show();
        }
    }

而这段代码...

   ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    componentInfo.getPackageName(); 
    Toast.makeText(this, "packageName: " + componentInfo.getPackageName(), Toast.LENGTH_LONG).show();

我的问题:

  1. 还有其他方法可以解决我的问题吗?也许用另一种方法在一个会话中获取所有应用程序?
  2. 有没有不使用 GET_TASKS 的另一种解决方案?(已弃用)
4

0 回答 0