The Android app goes backstage and the foreground is judged

Source: Internet
Author: User

According to the simplest way of thinking, all the activity of an app is onstop after all, but maybe the user just cut out and glanced at the other program and jumped back. Technically, this judgment is fine, but from a user's point of view, the user is not really leaving our app. There is also a situation, it is necessary in the process before the background, to perform some operations, if the user switching very frequently, the operation is more time-consuming may produce some inefficiencies and waste. Therefore, the simplest solution is to add a delay, define a front and back of our app concept, that is, the app is not visible after a period of time to enter the background, and once from the background state display as to enter the foreground.

To judge that the app is in the background, pay attention to each activity's declaration cycle in the app, and it's a stupid way to use the same base class for all activities in the entire project, and to override the declaration cycle method in this base class for monitoring.

But there is also an easy way to listen to the entire app lifecycle change for all activity: application.registeractivitylifecyclecallbacks ( Application.activitylifecyclecallbacks). This method can register multiple callback, not only register one, so even if there are other places (the statistical SDK often used) this is not affected.

Judging activity's display and hiding needs to use a pair of methods in the activity lifecycle, set as foreground when displayed, and set as background when hidden.

The first thing to consider is onstart/onstop, but soon the problem is discovered, in one activity start another activity, the OnStop method of the first activity is executed after the second activity's OnStart, Causes an error in the front and back of the last decision. The onstart is précis-writers as an opening parenthesis, and the onstop précis-writers is a closing parenthesis, then after performing the operation to start another activity, the sequence of execution is: "(()", you can see that there is still activity in the display state, but the last execution is OnStop, The OnStop will be set to the background state, so the state is wrong. This logic can also be corrected by other means, but it is undoubtedly more complex.

You can simply use Onresume/onpause instead of Onstart/onstop, where the invocation sequence of the two methods is expressed in parentheses: "() (", the last activity is the display state, and the last call is the method of Onresume setting the foreground.) Therefore, the onresume/onpause is used to determine the state of the front and rear tables.

Defines a class that is responsible for background judgment and management, which implements application.activitylifecyclecallbacks to monitor activity declaration cycle changes and maintains current state and distribution state change callbacks.

package Com.ajeyone.sample1;

Importandroid.app.Activity;Importandroid.app.Application;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.util.Log;Importjava.util.ArrayList; Public Final classBackgroundmanagerImplementsApplication.activitylifecyclecallbacks {
Public InterfaceBackgroundlistener {//provided to externally used callbacksvoidonbackgroundstatechanged ();//callback in the event of a change, the current state can be determined by the IsBackground method}Private Static FinalString TAG = "Backgroundmanager"; Private BooleanMbackground; Private Final LongMdelay; Private FinalArraylist<backgroundlistener> mbackgroundlisteners =NewArraylist<>(); Private FinalHandler Mhandler =NewHandler (); Private FinalRunnable mchangetobackgroundrunnable =NewRunnable () {//delayed execution of Runnable, set to background with a delay @Override Public voidrun () {SetBackground (true); } }; Backgroundmanager (Longdelay) {//package access, cannot create objects anywhere else, of course, you can use Singleton. Mdelay=delay;//delay time is determined by external} Public voidRegisterbackgroundlistener (Backgroundlistener Listener) {//need to listen this method can be used to register callbackssynchronized(mbackgroundlisteners) {mbackgroundlisteners.add (listener); } } Public voidUnregisterbackgroundlistener (Backgroundlistener Listener) {//guaranteed to be unregistered when not in use, especially when activity is usedsynchronized(mbackgroundlisteners) {mbackgroundlisteners.remove (listener); } } Public BooleanIsBackground () {returnMbackground; } Private voidSetBackground (Booleanbackground) {LOG.D (TAG,"SetBackground:" +background); BooleanOld =Mbackground; Mbackground=background; if(Old! =background) {//Prevent redundant callbacks, only notify LOG.D when changes occur (TAG,"Setbackground:state Changed"); for(Backgroundlistener listener:mbackgroundlisteners) {listener.onbackgroundstatechanged (); } }} @Override Public voidonactivitycreated (activity activity, Bundle savedinstancestate) {log.d (TAG,"Onactivitycreated:" +activity); } @Override Public voidonactivitystarted (activity activity) {LOG.D (TAG,"Onactivitystarted:" +activity); } @Override Public voidonactivityresumed (activity activity) {LOG.D (TAG,"Onactivityresumed:" +activity); Mhandler.removecallbacks (mchangetobackgroundrunnable); Cancels the delay execution of the runnable SetBackground (false); As long as the display, directly set to the foreground, if not shown before it is already the foreground, there will be no callback} @Override Public voidonactivitypaused (activity activity) {LOG.D (TAG,"Onactivitypaused:" +activity); Mhandler.postdelayed (mchangetobackgroundrunnable, Mdelay); After hiding, start timing, defer background conversion} @Override Public voidonactivitystopped (activity activity) {LOG.D (TAG,"Onactivitystopped:" +activity); } @Override Public voidonactivitysaveinstancestate (activity activity, Bundle outstate) {log.d (TAG,"Onactivitysaveinstancestate:" +activity); } @Override Public voidonactivitydestroyed (activity activity) {LOG.D (TAG,"Onactivitydestroyed:" +activity); }}

Use the custom application class: Provides methods to get Backgroundmanager and register callback

 PackageCom.ajeyone.sample1;Importandroid.app.Application; Public classMyApplicationextendsApplication {Private Static Final LongBackground_delay_ms = 30000; Private StaticMyApplication sinstance; PrivateBackgroundmanager Mbackgroundmanager; @Override Public voidonCreate () {Super. OnCreate (); Sinstance= This; Mbackgroundmanager=NewBackgroundmanager (Background_delay_ms);    Registeractivitylifecyclecallbacks (Mbackgroundmanager); }     Public StaticMyApplication getinstance () {returnsinstance; }     PublicBackgroundmanager Getbackgroundmanager () {returnMbackgroundmanager; }}

Activity to listen on:

 PackageCom.ajeyone.sample1;Importandroid.content.Intent;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportAndroid.view.View; Public classMainactivityextendsAppcompatactivityImplementsBackgroundmanager.backgroundlistener {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Myapplication.getinstance (). Getbackgroundmanager (). Registerbackgroundlistener ( This); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Myapplication.getinstance (). Getbackgroundmanager (). Unregisterbackgroundlistener ( This); Do not forget to unregister} @Override Public voidonbackpressed () {Movetasktoback (true); }    Private voidshowbackgroundstate () {BooleanBackground =myapplication.getinstance (). Getbackgroundmanager (). IsBackground (); LOG.D ("Main", "Showbackgroundstate:" +background); } @Override Public voidonbackgroundstatechanged () {showbackgroundstate (); }     Public voidonopendetail (view view) {startactivity (NewIntent ( This, Detailactivity.class)); Open another activity to see the front and back effects}}

Code on GitHub: Samplebackground

The Android app goes backstage and the foreground is judged

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.