Android implements the monitoring application back to the foreground from the background

Android implements the monitoring application back to the foreground from the background

In application development, there may be a scenario where the application has a main page, and then click the return button or HOME button on the main page to return to the desktop, and then open the application to return to the main page of the application. When we return to the homepage again, we may need to update some data or do some other operations.

Then it may be easy to think of a way: monitor the return key or the HOME key, set a flag on the homepage when the user clicks the return key or the HOME key, and then judge based on the status of the flag when the user comes back again.

However, reality is often not so satisfactory. Return by the event can be as simple onKeyDown()or onBackPressed()go listen to; but the event is no law in the HOME key onKeyDown()to listen to, there are some online can be done by broadcast or some other troublesome way, but it is easy for me to think of a different ROM will There are other compatibility issues.

So I thought of another solution.

Android's Applicationhave this one interface ActivityLifecycleCallbacks, it can monitor all applications within Activitythe life-cycle approach. So can we start with this.

Think about it, we go to the main page mainly in this scenario:

1. The desktop -> main page 

life cycle is as follows: ... - (click HOME or return) --> main page #onPause - (reopen the application) --> main page #onResume -> ...

2. The

life cycle of subpage -> main page is as follows: ... -> subpage #onPause -> ... -> main page #onResume ->...

So seeing here, you can basically find a solution. As long as we know that the main page was called last time onPause, this time the main page was called onResume, then we can be sure that our application is coming back from other places, of course, including the desktop or other apps. The main code is as follows:

public class AppRunningStatusCallbacks implements Application.ActivityLifecycleCallbacks {

private boolean mMainOnPaused = false;
private boolean mMainOnResumed = false;

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {
mMainOnResumed = (activity instanceof MainActivity);
if (mMainOnPaused && mMainOnResumed) {
//
//
}
}

@Override
public void onActivityPaused(Activity activity) {
mMainOnPaused = (activity instanceof MainActivity);
}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}
}

It's simple, so it's achieved.