We know that when we press the return or home key to exit the application's interface, the application is suspended in the background. The advantage of this design is that because the application is cached in memory by the system, the application can be started quickly by invoking the cache when the user opens the application. Of course, due to today's memory and processor power limitations, some processes are automatically closed by the system.
So how do I tell if the app is in the foreground or backstage, and the app goes back to the foreground from backstage?
See generally are runningprocess or runningtasks to judge the application in the foreground or backstage
In fact, Android provides a callback in SDK 14. Activitylifecyclecallbacks, you can get the lifecycle callback for all of the app's activity through this callback.
Count number of public class application extends Android.app.Application {private int activitycount;//activity private Boo
Lean isforeground;//Whether in the foreground @Override public void OnCreate () {super.oncreate (); Registeractivitylifecyclecallbacks (New Activitylifecyclecallbacks () {@Override public void onactivitycreated ( Activity activity, Bundle savedinstancestate) {} @Override public void onactivitystarted (activity activi
ty) {activitycount++;
@Override public void onactivityresumed (activity activity) {} @Override public void onactivitypaused {} @Override public void Onactivitys Topped (activity activity) {activitycount--; if (0==activitycount) {isforeground=false;
@Override public void onactivitysaveinstancestate (activity activity, Bundle outstate) {
} @Override public void onactivitydestroyed (activity activity) {}});
} }
This callback is written in application, and you can register at application initialization.
These callbacks allow us to place this count in OnStart () and OnStop (). Activitycount==1, then is the front desk, activitycount==0, that is backstage. That's a pretty simple judgment.
Public abstract class BaseClass extends Appcompatactivity {
Determines whether the current application is running
//need to request Gettask permissions
Private Boolean isapplicationbroughttobackground () {
Activitymanager am = (activitymanager) getsystemservice ( Context.activity_service); list<activitymanager.runningtaskinfo> tasks = am.getrunningtasks (1);
if (!tasks.isempty ()) { ComponentName topactivity = tasks.get (0). topactivity;
if (!topactivity.getpackagename (). Equals (Getpackagename ()) {return
true; } } return false; }
public boolean wasbackground= false; Declares a Boolean variable that records the current active background
@Override public void OnPause () {
super.onpause ();
if (Isapplicationbroughttobackground ())
wasbackground= true; }
public void Onresume () {
super.onresume ();
if (wasbackground) {//
log.e ("AA", "back to foreground from background"); } wasbackground= false; }}
Thank you for reading, I hope to help you, thank you for your support for this site!