By background, I mean none of the application\'s activities are currently visible to the user?
You can use ComponentCallbacks2 to detect if the app is in background. BTW this callback is only available in API Level 14 (Ice Cream Sandwich) and above.
You will get a call to the method:
public abstract void onTrimMemory (int level)
if the level is ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
then the app is in background.
You can implement this interface to an activity
, service
, etc.
public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 {
@Override
public void onConfigurationChanged(final Configuration newConfig) {
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
// app is in background
}
}
}