Aug 18, 2011

Android: Check application is running ?

Android has different application lifecycle, Many times user press Home hardware button and application goes in background, Application is still running but it's in background, Now We want to identify that application is running in background or not. It require when we don't want to create new instance of Activity. Android SDK provide class named ActivityManager. Using ActivityManager we can check application is running in background.

Here is the simple code for the same. you just need to change package name as per your requirement.

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

Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClass().getSimpleName());

ComponentName componentInfo = taskInfo.get(0).topActivity;
//if  app is running
if(componentInfo.getPackageName().equalsIgnoreCase(*Package Name*))
 //do the implementation for if your app is running