我试图获取用户在会话中打开的所有应用程序名称(会话以解锁手机开始,最后关闭屏幕)。
首先,我试图将当前的应用程序放在前台。我在后台使用服务并尝试了不同的代码:
的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();
我的问题: