Determining the current foreground application from a background task or service

dhaiwat picture dhaiwat · Jan 30, 2010 · Viewed 104.3k times · Source

I wish to have one application that runs in the background, which knows when any of the built-in applications (messaging, contacts, etc) is running.

So my questions are:

  1. How I should run my application in the background.

  2. How my background application can know what the application currently running in the foreground is.

Responses from folks with experience would be greatly appreciated.

Answer

Oliver Pearmain picture Oliver Pearmain · Oct 1, 2012

With regards to "2. How my background application can know what the application currently running in the foreground is."

Do NOT use the getRunningAppProcesses() method as this returns all sorts of system rubbish from my experience and you'll get multiple results which have RunningAppProcessInfo.IMPORTANCE_FOREGROUND. Use getRunningTasks() instead

This is the code I use in my service to identify the current foreground application, its really easy:

ActivityManager am = (ActivityManager) AppService.this.getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

Thats it, then you can easily access details of the foreground app/activity:

String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
PackageManager pm = AppService.this.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

This requires an additional permission in activity menifest and works perfectly.

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