3

How may I get the current running application?

I want to check if the application is running or not in service. I used the following code for that.

       ActivityManager activityManager =
       (ActivityManager)
       this.getSystemService(ACTIVITY_SERVICE );

   PackageManager pm =getPackageManager();
   procInfos = activityManager.getRunningAppProcesses();

But it is returning me list of several applications, even if I pressed back button on their home screen. The running app list is still showing them in the list. But I want that list to show only the apps in foreground.

So, how to differentiate between foreground and background running apps?

Or in other words, how to detect current foreground running applications, or which are not destroyed. I don't want to get background running apps.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Narendra Singh
  • 3,990
  • 5
  • 37
  • 78
  • 1
    Well, one thing I can tell you is that pressing back on an app's home screen calls `onStop`, *not* `onDestroy`, so that's why they are still showing up. [This link](http://stackoverflow.com/questions/2166961/determining-the-current-foreground-application-from-a-background-task-or-service) may also help. – Mxyk Jun 28 '12 at 14:23
  • You may be interested in this: [http://stackoverflow.com/questions/2314969/how-to-determine-if-one-of-my-activities-is-in-the-foreground](http://stackoverflow.com/questions/2314969/how-to-determine-if-one-of-my-activities-is-in-the-foreground) – ekholm Jun 28 '12 at 14:24

1 Answers1

7

You can try this code it gives the package of the currently active screen:

ActivityManager am = (ActivityManager) this
                .getSystemService(ACTIVITY_SERVICE);

// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

ComponentName componentInfo = taskInfo.get(0).topActivity;
if(!componentInfo.getPackageName().equals("your.package.name"))
{
    //Do your stuff
}

You might need the permission

<uses-permission android:name="android.permission.GET_TASKS" />
dharmin007
  • 1,612
  • 16
  • 17
  • 3
    `ActivityManager#getRunningTasks()` is deprecated in API 21, and **doesn't even return the correct result anymore** (functionality restricted for security reasons). – Vicky Chijwani Mar 14 '16 at 17:56