Activities in Android

To understand Activity, you must first understand the following concepts:

Application components

App components are the basic building blocks of Android apps. Each component is an entry point through which the system or users can enter your application. Some components depend on other components.

There are four different application component types:

  • Activity
  • Serve
  • broadcast receiver
  • content provider

Each type has a different purpose and lifecycle, which defines how the component is created and destroyed. The following sections describe the four types of application components.

Application Basics | Android Developers | Android Developers (google.cn)

This is part of the official documentation for Android developers

1.What is Activity

Activity is an Android application component that provides screens for interaction. Each Activity gets a window for drawing its user interface. The window can fill the screen or be smaller than the screen and float on top of other windows.

An application is usually composed of multiple activities that are loosely related to each other. Generally, an Activity in the application is designated as the main activity, which means that the Activity is presented to the user when the application is first launched. To set Activity as the main activity, as shown in the code below, you need to add the following content to the AndroidManifest file

<application>
     ....
    <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
     </activity>
     ....
</application> 

Of course, Activities can jump to each other to perform different operations. Whenever a new Activity is started, the old Activity will be stopped, but the system will retain the Activity in the stack, that is, the return stack. When a new Activity is started, the system will also push it to the return stack and obtain the user’s operation focus. When the user completes the current activity and presses the return button, the system pops it from the stack, destroys it, and then restores the previous activity.

When an Activity is stopped because a new Activity is started, the code system will notify it of this change in status through the Activity’s life cycle callback method. Activity may have several changes due to state changes, and each callback will provide an opportunity to perform a specific operation corresponding to the state.

Let’s start with the basic knowledge of creating and using Activity (including a comprehensive explanation of how the Activity life cycle works)

2. Create Activity

To create an Activity, you must create a subclass of Activity. In the subclass, implement the callback method called by the system when the Activity transitions between various states of the life cycle, such as when creating an Activity, stopping an Activity, resuming an Activity, or destroying an Activity. The code created by default for new projects in Android Studio is

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

onCreate() method: A method that must be implemented. The system calls this method when creating an Activity. You should initialize the necessary components of the Activity within the implementation. You must call setContentView() in this method to define the Activity user interface layout (XML file)

3. Declare Activity in the manifest file

Each new Activity needs to add the following content to the AndroidManifest file, and add the element as a child of the element

<manifest ... >
  <application...>
      <activity android:name=".ExampleActivity" />
      ...
  </application...>
  ...
</manifest>

4. Start Activity

This section describes how to start the Activity. As the main activity, it will be created by the system when the application is opened, and the user not only needs the main activity interface, but also needs the jump of the interface, and the jump of the interface also starts other activity interfaces (Activities).

In this section, we only mention the use of display Intent to jump to activities. The code is as follows

Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
//this is the context of this Activity; the second parameter is the Activity.class you want to jump to

5.End Activity

End the Activity by calling the Activity’s finish() method. You can also end the previously started activity by calling finishActivity().

Understanding of finishActivity():

If you start ActivityA through MainActivity (using the startActivityForResult method), then you need to override the onActivityResult() method in the MainActivity class.
Then, you can end ActivityA through the finishActivity() method in onActivityResult()

6.Manage Activity life cycle

A cycle is the various states an activity goes through from the beginning to the end. The life cycle is the various states that an activity goes through from the beginning to the end. The transition from one state to another, from nothing to something and then to nothing, is called a life cycle.

Activity essentially has four states:

1. Running (Active/Running): Activity is in the active state. At this time, Activity is on the top of the stack, is visible, and can interact with the user.

2. Paused: When the Activity loses focus, or is placed on the top of the stack by a new non-full-screen Activity, or by a transparent Activity, the Activity is converted to the Paused state. It will not be destroyed at this moment, but it has lost the ability to interact with the user. All its status information and member variables are still there. It can only be recycled by the system when the system memory is tight.

3. Stopped: When the Activity is completely covered by the system, the covered Activity will enter the Stopped state and is no longer visible, but the resources have not been recovered.

4. System recycling (Killed): When the Activity is recycled by the system, the Activity is in the Killed state.

If an activity is in a stopped or suspended state, it will be finished or killed when the system lacks memory. In this abnormal situation, the system will call the onSaveInstance() method to save the information before killing or ending. At the same time, when the Activity is moved to the foreground, the Activity will be restarted and the onRestoreInstance() method will be called to load the retained information. Keep it as it is.

Between the four common states above, there are other life cycles that serve as transitions between different states and are used to convert between different states. The specific description of the life cycle is as follows.

The column named “Can it be terminated afterwards?” indicates whether the system can terminate the process hosting the activity at any time after the method returns without executing another line of activity code.

Together, these methods define the entire life cycle of the Activity. You can monitor three nested loops in the Activity lifecycle by implementing these methods:

The entire life cycle of an Activity occurs between onCreate() calls and onDestroy() calls. Your activity should perform “global” state setup (such as defining layout) in onCreate() and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background that downloads data from the network, it might create the thread in onCreate() and then stop the thread in onDestroy().
The visible life cycle of an activity occurs between onStart() calls and onStop() calls. During this time, the user can see and interact with the activity on the screen. For example, when a new activity starts and this activity is no longer visible, the system calls onStop(). You can preserve the resources needed to display the activity to the user between calls to these two methods. For example, you could register a BroadcastReceiver in onStart() to monitor changes affecting the UI, and unregister it in onStop() when the user can no longer see what you’re showing. Throughout the activity’s life cycle, the system may call onStart() and onStop() multiple times as the activity alternates between visible and hidden states from the user.
The foreground life cycle of an Activity occurs between onResume() calls and onPause() calls. During this time, the activity is in front of all other activities on the screen and has user input focus. An activity can move in and out of the foreground frequently-for example, onPause() is called when the device goes to sleep or when a dialog box appears. Because this state may transition frequently, the code in both methods should be moderately lightweight to avoid making the user wait due to slow transitions.

7. Example Verification Activity Activity Cycle

Next, we will use a small example to verify the function callback.

The code is very simple. Create two activities and corresponding interfaces. Each interface has only one button and TextView. The button is set to be a click event for page jump. There is a Log output in each callback function, so the verification results can also be viewed by viewing Logcat. The MainActivity code is posted below. The jumped SecondActivity code is similar to it, so it is not posted. Just go to the MainActivity code. to modify.

package com.example.martinzou.android_exp_2;

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

public class MainActivity extends AppCompatActivity {
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("MainActivity","onCreate() is called");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("MainActivity","onStart() is called");
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("MainActivity","onResume() is called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("MainActivity","onPause() is called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("MainActivity","onStop() is called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("MainActivity","onDestroy() is called");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("MainActivity","onRestart() is called");
    }
}

The two layout files designed are as follows

1. Run it on your mobile phone and open it, and check the Logcat as shown below

When the mobile phone loads the application to the display interface, Activity startup->onCreate()->onStart()->onResume() is called in sequence. At this time, MainActivity is in an interactive state.

2. When I press the Home button and return to the main interface, the Logcat is

Click the Home button to return to the main interface (Activity is not visible)–>onPause()–>onStop() are called in sequence.

3. After clicking the Home button to return to the main interface, and clicking App again to return to Activity, the Logcat result is as follows

We can find that when returning to the Activity, the onRestart method, onStart method, and onResume method are called. therefore,

When we return to the original Activity again –>onRestart()–>onStart()–>onResume() are called in sequence.

4. When I press the return key, the app exits and the MainActivity is destroyed (Destroyed)

onPause()->onStop()->onDestroy() is called in sequence, and MainActivity is destroyed.

5. When loading the application to enter the main interface and clicking the button to jump to the page, check the Logcat as

The onPause() and onStop() methods were called in the original Activity. At the same time, we also found that the life cycle method of SecondActivity can be called back only after MainActivity completes onPause(), so this is why the onPause() method cannot operate time-consuming tasks. reason.

6. When we click the Back key to return, the Logcat result is

After clicking, SecondActivity’s onPause() method, onStop() method, and onDestroy() method are called in sequence, and MainActivity’s onRestart(), onStart(), and onResume() are called in sequence. MainActivity’s life cycle method can be called back after SecondActivity completes onPause().

7. When we click the button in the SecondActivity interface to jump to MainActivity, the Logcat is as shown below

You will find that MainActivity does not call onRestart(), but directly calls onCreate(), onStart(), onResume(). After the jump, SecondActivity is not destroyed. The TV is in the onStop() state, which indicates that SecondActivity() and has not been destroyed.

Summary: When the Activity starts, onCreate(), onStart(), onResume() will be called in sequence, and when the Activity retreats to the background (invisible, clicks Home or is completely covered by a new Activity), onPause() and onStop() ) will be called in turn. When the Activity returns to the foreground (returns to the original Activity from the desktop or returns to the original Activity after being overwritten), onRestart(), onStart(), and onResume() will be called in sequence. When the Activity exits and is destroyed (click the back button), onPause(), onStop(), and onDestroy() will be called in sequence. At this point, the entire life cycle method callback of the Activity is completed.

Original link: Android layout experiment (LinearLayout, RelativeLayout, TableLayout)-CSDN blog