I've tried to get all names of applications which the user opened in a session (session start with unlocking phone and ends with turning off the screen).
As first I've tried to get the current app in the foreground. I use a service in the background and tried different code:
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();
}
It works fine in my own app, but if another app is in the foreground I get as package just "com.sec.android.app.launcher" ("TouchWiz-Start" as foregroundTaskAppName). I also tried this code in TaskListenerService.java with the same result:
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();
}
}
And this code...
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();
My Questions:
- Is there another way to resolve my problem? Maybe with another approach to get all apps in a session?
- Is there another solution without using GET_TASKS? (deprecated)