You can define a superclass for all your activities and track the state of the app. If all activities are in stopped state - app in the background, otherwise - in the foreground. In onStart()
and onStop()
methods of your super activity you can increment and decrement the number of visible activites. Then in onStart()
and onStop()
check if there was any currently visible activity. If no - app becomes active/inactive and you can call your method:
public class SuperActivity extends Activity {
private static int sVisibleActivitiesCount;
@Override
public void onStart(){
super.onStart();
if (SuperActivity.sVisibleActivitiesCount == 0) {
onAppBecomesActive();
}
SuperActivity.sVisibleActivitiesCount++;
}
@Override
public void onStop(){
super.onStart();
SuperActivity.sVisibleActivitiesCount--;
if (SuperActivity.sVisibleActivitiesCount == 0) {
onAppBecomesInactive();
}
}
private void onAppBecomesActive() {
// Do some staff
}
private void onAppBecomesInactive() {
// Do some staff
}
}
The second approach is to use ActivityLifecycleCallbacks (min API 14) for monitoring activities lifecycle and track application state in a single place without having a super class for all activities. So I would rather use this approach if your app has minSdkVersion="14".