Code is the best teacher

Summary 1.

Activity is the first of four components

2.Activity lifecycle

  • Typical life cycle:

Changes to an Activity’s life cycle with user participation;

  • Life cycle in exceptional cases:

An Activity is reclaimed by the system or destroyed and rebuilt because the Configuration of the current device has changed

2.1 Typical life cycle

  • When a user presses the back key to rollback, the callback is as follows: onPause -> onStop -> onDestroy

2.2 Abnormal life cycle

  • If the screen is suddenly rotated, the Activity is destroyed and recreated by default due to a change in system configuration
  • When an Activity is terminated in an abnormal case, onSaveInstanceState is called to save the current state of the Activity
  • When an Activity is terminated unexpectedly, the Activity calls onSaveInstanceState to save the data. The Activity then delegates the data to the Window, which in turn delegates the top-level container above it to save the data. The top container is a ViewGroup, which is most likely a DecorView. Finally, the top-level container notifies its children to save the data, and the entire data saving process is complete
  • Once onRestoreInstanceState is called, the Bundle savedInstanceState parameter must have a value, so we don’t have to check whether it’s empty or not; If onCreate is started normally, the Bundle savedInstanceState parameter is null, so you have to make extra checks

2.3 configChanges

You can add the orientation value to the configChanges property if you don’t want your Activity to be recreated while the screen rotates

android:configChanges="orientation"
android:configChanges="orientation|screenSize"
android:configChanges="orientation|keyboardHidden"
Copy the code

The Activity is not recreated, and instead of calling onSaveInstanceState and onRestoreInstanceState to store and restore data, the system calls the Activity’s onConfigurationChanged method

There are many items in the table above, but the only ones we use are locale, orientation, and keyboardHidden

3. Start the Activity

  1. Requests to start an Activity are handled by Instrumentation
  2. Instrumentation sends requests to AMS through Binder
  3. The Activity Manager Service (AMS) maintains an ActivityStack and is responsible for synchronizing the state of activities in the stack
  4. AMS uses ActivityThread to synchronize Activity state and complete lifecycle method calls

4. Start the Activity mode

  • AddFlags takes precedence over XML
  • When clearTaskOnLaunch sets this property, all activities on the Activity are cleared each time the Activity is returned
  • TaskAffinity: Identifies the name of the task stack required by an Activity. By default, the name of the task stack required by all activities is the package name of the application
  • Using the startActivityForResult() method to start another Activity, the system returns activity.result_canceled, There is no waiting for a return, because Android imposes restrictions on both startup modes in the Framework

Basic: Different Task stacks cannot perform data binding, and if necessary, can only perform data binding with intEnts

4.1 Standard Mode: Standard

  1. Default startup mode
  2. Create a new instance of the activity each time it starts
  3. The activity is in the stack of whoever started the activity instance
  4. An error is reported when we use the ApplicationContext to start an Activity in Standard mode

Cause: An Activity in Standard mode enters the task stack to which it is started by default. ApplicationContext has no task stack; Intent.flag_activity_new_task (intent.flag_activity_new_task) intent.addFlags(intent.flag_activity_new_task

4.2 Stack Top Reuse mode -singleTop

  1. If the target activity instance is at the top of the stack, the activity is not recreated, and the onNewIntent() method is called instead of onCreate() and onStart().
  2. If there is no target instance at the top of the stack, recreate the activity

4.3 In-stack Reuse mode -singleTask [AndroidManifest clearTop]

  1. The onNewIntent() method is called. OnCreate () and onStart() are not called.
  2. When the activity is started, it looks for the target stack, creates the stack if it doesn’t exist, and then creates the instance
  3. If the target stack exists, it looks for the target activity in the stack and creates it if it does not.
  4. If the target activity exists on the target stack and is not at the top of the stack, the instance above the activity is pushed off the stack and the activity is pushed to the top of the stack

4.4 Single-instance Mode -singleInstance

  1. Enhanced singleTask mode, where the activity runs in a separate stack

4.5 the Intent of Flags

  1. FLAG_ACTIVITY_NEW_TASK: Specifies the singleTask startup mode for an activity
  2. FLAG_ACTIVITY_SINGLE_TOP: specify singleTop
  3. FLAG_ACTIVITY_CLEAR_TOP: works with FLAG_ACTIVITY_NEW_TASK and has the same effect as singleTask
  4. FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS:Activity does not appear in the list of historical activities, a one-time Activity

5.Activity Data transfer

5.1 Carrying Data

Step1 :Activity1 sends data

String data = "hello world";
Intent intent = new Intent(MainActivity.this,FirstActivity.class);
intent.putExtra("mydata",data);
startActivity(intent);
Copy the code

Step2 :Activity2 accepts the data

Intent intent = getIntent();
String data = intent.getStringExtra("mydata");
Toast.makeText(this."The value passed in is" + data, Toast.LENGTH_SHORT).show();
Copy the code

5.2 Returning Data

Step1: Activity1 startup mode: Requires data to be returned

Intent intent = new Intent(MainActivity.this, FirstActivity.class);
startActivityForResult(intent, 1);
Copy the code

Step2: set activity2 to return data

Intent intent = new Intent();
intent.putExtra("data_return"."hello");
setResult(RESULT_OK,intent);
finish();
Copy the code

Step3 :activity1 receives the returned data

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    String returnedData = data.getStringExtra("data_return");
                    Log.e("MainActivity",returnedData); }}}Copy the code

6. Manage activities globally

Only provide ideas, actual development as needed to change to soft reference mode

Step1: the Activity management class

public class ActivityCollector{
     public static List<Activity> activities = new ArrayList<>();
    
     public static void addActivity( Activity activity ){
          activities.add( activity );
     }
    
     public static void removeActivity( Activity activity ){
           activities.remove( activity );
     } 

     public static void finishAll(a){
            for( Activity activity : activities){ activity.finish(); }}}Copy the code

step2:BaseActivity

public class BaseActivity extends AppCompatActivity{
     @Override
     protected void onCreate( Bundle savedInstanceState ){
          super.onCreate( savedInstanceState );
          Log.d( "BaseActivity" , getClass().getSimpleName() );
          ActivityCollector.addActivity(this);
     }

      @Override
      public void onDestory(a){
           super.onDestory();
           ActivityCollector.removeActivity(this); }}Copy the code

step3:XxxActivity

public class XxxActivity extends BaseActivity{
    //....
    private void exitApp(a){
        ActivityCollector.finishAll();
        //or force exit
        //android.os.Process.killProcess(android.os.Process.myPid());
    }
    / /...
}
Copy the code