Question: I'm trying to implement some automatic logout code for my Application on Android.

I need to detect if all the activities belonging to an Application have entered the background as opposed to working with `onPause()` and `onResume()` for each individual activity. iOS has a helpful `applicationDidEnterBackground:` method that I could utilize, but I'm unable to find a similar function in Android's `Application` class.

One approach seems to be to have an `AtomicInteger` counter and increment it once an activity becomes visible and decrement it when it's finished or onStop() gets called. So if the counter becomes zero, I can start a service that runs in the background and handles the logout. Is this how it's usually done?

Answer: 
There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().
Create an Application class and include in the manifest 

```
<application
        android:name="com.example.hello.MyApplication"

public class MyApplication extends Application implements
        ActivityLifecycleCallbacks, ComponentCallbacks2 

```

override the following method

```
@Override
public void onTrimMemory(int level) {
        // this method is called when the app goes in background.
        // you can perform your logout service here
        super.onTrimMemory(level);
    }

```

this is valid of API level 14 and above.

You can even perform the the logout based on the amount of time the app is in background, which i would suggest is a better option. here is what you can do to create as "session timeout"

1. save the time stamp in `SharedPreferences` inside the `onTrimMemory(int level)` method
2. on all your activities onStrat() get the time stamp from sharedPref and compare it with current time. based on this you can perform a logout.
3. and clear the shared pref on onCreat of MyApplication