Use ActivityLifecycleCallbacks Android App Management Activity and distinguish front and back

A, ActivityLifecycleCallbacks Interface introduction

Official Address: https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks

In the Android API Application class after 14, provides us with a registration application lifecycle callback method, used for application lifecycle centralized management, this interface is called registerActivityLifecycleCallbacks, it can register their ActivityLifeCycleCallback, each an Activity life cycle will correspond to the callback method here.

With ActivityLifeCycleCallback interfaces, before we can do what we want to develop a similar number of restrictions such as Activity-related needs, because all the Activity life cycle callback will be here, we can harness processing according to the conditions.

Activity life cycle Pictured: https://developer.android.com/images/activity_lifecycle.png ;

ActivityLifecycleCallbacks list of methods Documentation: https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks

Both almost one to one, whether it is done or Activity Activity limit state statistics are very convenient, but there is also a void onActivitySaveInstanceState (Activity activity, Bundle outState) method, we are very convenient to store state data Activity .

Use ActivityLifecycleCallbacks we can perform similar functions as follows:

1. Activity limit specifies the number of

2. Control in a particular case will be only one was open Activity

3. Analyzing the state of foreground and App

Two, ActivityLifecycleCallbacks applications

Application.ActivityLifecycleCallbacks is an interface Application, use is also very simple, just call registerActivityLifecycleCallbacks method to complete the registration. Application.ActivityLifecycleCallbacks is triggered after the corresponding life-cycle approach listens parent class will be called Activity in the life of the method.

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

public class LifecycleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was Created"+"activity==null   "
                        +(activity==null)+"     activity.isFinishing()  "+(activity.isFinishing())+"    activity.isDestroyed()  "+activity.isDestroyed());
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was Started"+"activity==null   "
                            +(activity==null)+"     activity.isFinishing()   "+(activity.isFinishing())+"   activity.isDestroyed()  "+activity.isDestroyed());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                 Log.e("Lifecycle",activity.getLocalClassName()+" was oResumed"+"activity==null   "
                        +(activity==null)+"activity.isFinishing()   "+(activity.isFinishing())+"activity.isDestroyed() "+activity.isDestroyed());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was Pauseed"+"activity==null   "
                        +(activity==null)+"activity.isFinishing()   "+(activity.isFinishing())+"activity.isDestroyed()  "+activity.isDestroyed());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was Stoped"+"activity==null    "
                        +(activity==null)+"activity.isFinishing()   "+(activity.isFinishing())+"activity.isDestroyed() "+activity.isDestroyed());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was SaveInstanceState"+"activity==null "
                        +(activity==null)+"activity.isFinishing()   "+(activity.isFinishing())+"activity.isDestroyed()  "+activity.isDestroyed());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.e("Lifecycle",activity.getLocalClassName()+" was Destroyed"+"activity==null"
                        +(activity==null)+"  activity.isFinishing()  "+(activity.isFinishing())+"  activity.isDestroyed()"+activity.isDestroyed());
            }
        });
    }
}

Application declared in the manifest, without adding additional code in the Activity monitoring can be achieved:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    public static final String LIFECYCLE = "MainActivity:Lifecycle";

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        Log.e(LIFECYCLE, "onCreate() is Running__before super.onCreate called");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(LIFECYCLE, "onCreate() is Running__after super.onCreate called");
    }

    @Override
        protected void onRestart() {
        Log.e(LIFECYCLE, "onRestart() is Running__before super's called");
        super.onRestart();
        Log.e(LIFECYCLE, "onRestart() is Running__after super's called");
    }

    @Override
        protected void onStart() {
        Log.e(LIFECYCLE, "onStart() is Running__before super.onStart called");
        super.onStart();
        Log.e(LIFECYCLE, "onStart() is Running__after super.onStart called");
    }

    @Override
        protected void onResume() {
        Log.e(LIFECYCLE, "onResume() is Running__before super.onResume called");
        super.onResume();
        Log.e(LIFECYCLE, "onResume() is Running__after super.onResume called");
    }

    @Override
        protected void onPause() {
        Log.e(LIFECYCLE, "onPause() is Running__before super's called");
        super.onPause();
        Log.e(LIFECYCLE, "onPause() is Running__after super's called");
    }

    @Override
        protected void onStop() {
        Log.e(LIFECYCLE, "onStop() is Running__before super's called");
        super.onStop();
        Log.e(LIFECYCLE, "onStop() is Running__after super's called");
    }

    @Override
        protected void onDestroy() {
        Log.e(LIFECYCLE, "onDestroy() is Running__before super's called");
        super.onDestroy();
        Log.e(LIFECYCLE, "onDestroy() is Running__after super's called");
    }

    public void toTask(View view) {
        startActivity(new Intent(this, TaskActivity.class));
        //finish();
    }
} 

Third, the use of front and back ActivityLifecycleCallbacks state determination App

Under normal circumstances App switching front and back are carried out according to Home, of course, there are other ways, but this time Activity life cycle is the same:

HOME button before and after the execution order switching station of Activity: onPause-> onStop-> onRestart-> onStart-> onResume

BACK key sequence before and after the switching station bond Activity: onPause-> onStop-> onDestroy-> onCreate-> onStart-> onResume

In fact, according to BACK button to exit the app is, and not a reception after switching.

Now we know that App switched from front to back all open Activity will go:

onPause->onStop

The background to the foreground all open Activity will go:

->onRestart->onStart->onResume

App switching front and back of all open Activity life cycle are the same, so I can record life cycle ActivityLifecycleCallbacks callback interface:

public  class the App the extends the Application {
     // record the total number of Activity 
    public  int COUNT = 0 ;
     Private  static the App mApp;
     public  static Stack <ActivityDetail> Store;
     // Product before the maximum number of pages, this test is only written to 2, all according to their own values provided 
    Private  static  Final  int MAX_ACTIVITY_DETAIL_NUM = 2 ; 

    @Override 
        public  void the onCreate () {
         Super .onCreate (); 
        mApp = the this ; 
        Store = new new Stack<>();
        registerActivityLifecycleCallbacks(new SwitchBackgroundCallbacks());
    }

    public static App getAppContext() {
        return mApp;
    }

    public static boolean toGoodsDetail(String id){

        if(store == null || store.empty()){
            return false;
        }
        for(ActivityDetail activityDetail : store){
            if(id.equalsIgnoreCase(activityDetail.getID())){ //当前商品的详情页已经打开
                activityDetail.finish ();
                 // this is that you need to add "Android.permission.STOP_APP_SWITCHES" user permissions in AndroidManifest.xml, provided that must be applied before the system can be.
                // the ActivityManager AM = (the ActivityManager) getAppContext () the getSystemService (Activity.ACTIVITY_SERVICE);.
                 // am.moveTaskToFront (activityDetail.getTaskId (), 0); 
                return  to true ; 
            } 
        } 
        return  to false ; 
    } 

    Private  class SwitchBackgroundCallbacks the implements ActivityLifecycleCallbacks { 

        @ Override 
            public  voidonActivityCreated (the Activity Activity, the Bundle the bundle) {
             IF (Activity the instanceof ActivityDetail) {
                 IF (store.size ()> = MAX_ACTIVITY_DETAIL_NUM) { 
                    store.peek () Finish ();. // remove the bottom of the stack before the page and finish, store listings maximum number of page 10 
                } 
                store.add ((ActivityDetail) Activity); 
            } 
        } 

        @Override 
            public  void onActivityStarted (the Activity Activity) {
             IF (COUNT == 0) { // the background to the foreground 
                Log.v ( "danxx", ">>>>>>>>>>>>>>>>>>> App cut to the front.");
            }
            count++;
        }

        @Override
            public void onActivityResumed(Activity activity) {

        }

        @Override
            public void onActivityPaused(Activity activity) {

        }

        @Override
            public void onActivityStopped(Activity activity) {
            count--;
            if (count == 0) { //前台切换到后台
                Log.v("danxx", ">>>>>>>>>>>>>>>>>>>App切到后台");
            }
        }

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

        }

        @Override
            public void onActivityDestroyed(Activity activity) {
            store.remove(activity);
        }
    }
    // 获取当前的Activity
    public Activity getCurActivity() {
        return store.lastElement();
    }
}

 

Guess you like

Origin www.cnblogs.com/renhui/p/11074604.html