How to know if the app goes to Background

With API Level 14 – Android 4.0, there is a Method in Application which is called onTrimMemory. The onTrimMemory is executed by the system with different levels ( TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_UI_HIDDEN, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, or TRIM_MEMORY_RUNNING_MODERATE). The interesting level is “TRIM_MEMORY_UI_HIDDEN”. This level can be used to know that the app is going to background.

The following example is a demonstration of the Application.onTrimMemory Method:


public class MyApplication extends Application {
// ...
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
notifyAppInBackground();
}
}
// ...
}

With this simple piece of code, you can check if your app is being sent to the background!