80

I am an Android developer and I want to write an if statement in my application. In this statement I want to check if the default browser (browser in Android OS) is running. How can I do this programmatically?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sjor
  • 1,438
  • 5
  • 17
  • 22

6 Answers6

158

Add the below Helper class:

public class Helper {

        public static boolean isAppRunning(final Context context, final String packageName) {
            final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
            if (procInfos != null)
            {
                for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
                    if (processInfo.processName.equals(packageName)) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

Now you can check from the below code if your desired App is running or not:

if (Helper.isAppRunning(YourActivity.this, "com.your.desired.app")) {
    // App is running
} else {
    // App is not running
}
Blacklight
  • 3,809
  • 2
  • 33
  • 39
dhaval
  • 7,611
  • 3
  • 29
  • 38
  • 3
    Thx, but as i see every time com.android.browser is running. When it is foreground, generally it's in 3rd or 4th position of the list, otherwise it is still in the list. So this statement every time returns true. How can i solve this problem? Only when the recent process is browser it must write "browser is running". – sjor Nov 18 '10 at 15:33
  • 1
    a field 'lru' in the RunningAppProcessInfo will give you the relative information of the application runtime for further reference check the doc page - http://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo.html – dhaval Nov 19 '10 at 11:03
  • for much finer detail you can maintain a time counter in your application. in one of my past app to display the process state just like gmail chat status we maintained the app time along with the importance value – dhaval Nov 19 '10 at 11:07
  • 1
    @dhaval is there any way to check that the app has now gone to background (i.e. no longer visible to the user)? – SMR Apr 22 '14 at 08:38
  • Is it any way to check process is pause or resume? – Unmerciful Jul 30 '14 at 09:40
  • Doesn't work if u have yours packages in main package. – Morozov Jun 22 '17 at 11:52
  • Does it work to detect activity of other apps? https://stackoverflow.com/questions/48699462/detect-app-starting-and-terminating-using-external-service-in-android – NoWar Feb 09 '18 at 06:21
  • Whoever got this code not working in killed/background states of app in Naugat?Marshmallow versions of android, Please check this answer once: https://stackoverflow.com/a/48302378/7445389 – amit pandya May 09 '19 at 18:26
  • It'll return only self process since API 21 – Troy Jun 19 '22 at 15:10
7

isInBackground is the status of app

ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
Boolean isInBackground = myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
Rajneesh Shukla
  • 1,048
  • 13
  • 21
1

You can check it by the following method

public static boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (ActivityManager.RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
            return true;
    }
    return false;
}
Android Dev
  • 1,496
  • 1
  • 13
  • 25
1

Best solution is :

Create an interface like this.

interface LifeCycleDelegate {
    void onAppBackgrounded();
    void onAppForegrounded();
}

Now add a class that handle all activity lifecycle callbacks.

public class AppLifecycleHandler implements 
 Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {

LifeCycleDelegate lifeCycleDelegate;
boolean appInForeground = false;

public AppLifecycleHandler(LifeCycleDelegate lifeCycleDelegate) {
    this.lifeCycleDelegate = lifeCycleDelegate;
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {
    if (!appInForeground) {
        appInForeground = true;
        lifeCycleDelegate.onAppForegrounded();
    }
}

@Override
public void onActivityPaused(Activity activity) {

}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}

@Override
public void onTrimMemory(int level) {
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        // lifecycleDelegate instance was passed in on the constructor
        appInForeground = false;
        lifeCycleDelegate.onAppBackgrounded();
    }
}

@Override
public void onConfigurationChanged(Configuration newConfig) {

}

@Override
public void onLowMemory() {

}
}

Now in a class extending Application

public class MyApplication extends Application implements 
 LifeCycleDelegate{
 @Override
public void onCreate() {
    super.onCreate();

    AppLifecycleHandler lifeCycleHandler = new 
    AppLifecycleHandler(MyApplication.this);
    registerLifecycleHandler(lifeCycleHandler);
}

@Override
public void onAppBackgrounded() {
    Log.d("Awww", "App in background");
}

@Override
public void onAppForegrounded() {
    Log.d("Yeeey", "App in foreground");
}

private void registerLifecycleHandler(AppLifecycleHandler lifeCycleHandler) {
    registerActivityLifecycleCallbacks(lifeCycleHandler);
    registerComponentCallbacks(lifeCycleHandler);
}
}

For More refer : https://android.jlelse.eu/how-to-detect-android-application-open-and-close-background-and-foreground-events-1b4713784b57

Rehan Sarwar
  • 994
  • 8
  • 20
Rohit Lalwani
  • 529
  • 7
  • 14
0
fun Context.isAppInForeground(): Boolean {

val application = this.applicationContext
val activityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningProcessList = activityManager.runningAppProcesses

  if (runningProcessList != null) {
     val myApp = runningProcessList.find { it.processName == application.packageName }
     ActivityManager.getMyMemoryState(myApp)
     return myApp?.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
  }

  return false
}
SohailAziz
  • 8,034
  • 6
  • 41
  • 43
0

If you are Using Kotlin

   private fun isAppRunning(context: Context, packageName: String): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        activityManager.runningAppProcesses?.apply {
            for (processInfo in this) {
                if (processInfo.processName == packageName) {
                    return true
                }
            }
        }
        return false
    }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154