Kyle Banks

Keep Track of Running Activities in Android, and When Your App is in the Background

Written by @kylewbanks on Mar 24, 2013.

Something that can be helpful in Android development is to know if your app is in the background, or if it is presently active. Determining this programmatically can be tricky, but it is by no means impossible. Using your Application object, you can register a listener for activity lifecycle changes, and keep track of your application's state.

In the following example I am only looking at the ActivityStopped and ActivityStarted events, but you should also be aware of Paused, Resumed, Destroyed and Created events, and account for them accordingly.

Be aware, that while it is possible to keep a reference to the top (active) activity, it is by no means a good idea to do so. Keeping references to destroyed activities is bound to give you nothing but trouble, so it's best to refrain from doing it.

private int numRunningActivities = 0;

@Override
public void onCreate() {
	super.onCreate();
	Log.i(TAG, "Application started");
	
	...
	
	//Listen for activity state changes
	this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
		
		@Override
		public void onActivityStopped(Activity activity) {
			Log.i(TAG, "Activity Stopped: " + activity.getClass().getCanonicalName());
			numRunningActivities--;
			
			if(numRunningActivities == 0) {
				Log.i(TAG, "No running activities left, app has likely entered the background.");
			} else {
				Log.i(TAG, numRunningActivities + " activities remaining");
			}
		}
		
		@Override
		public void onActivityStarted(Activity activity) {
			Log.i(TAG, "Activity Started: " + activity.getClass().getCanonicalName());
			numRunningActivities++;
		}
		
		@Override
		public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onActivityResumed(Activity activity) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onActivityPaused(Activity activity) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onActivityDestroyed(Activity activity) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
			// TODO Auto-generated method stub
		}
	});
}
Let me know if this post was helpful on Twitter @kylewbanks or down below!