Android's four active components (Activity)

EDITORIAL

Activity is an important component of Android applications, the number of programming languages, the program is initiated by the main () function, but we can not find in the Android project in main () function, which is due to start Android App is the way: through Android system to call a particular stage of its life cycle corresponding to a specific callback method to start the code Activity instance. For example, when a start is clicked App, Android system creates an instance of a Acticity you write and call their lifecycle deserve onCreate () and onStart () and other methods, we will later introduce specific. This part describes what individuals in Android Activity understanding (I am a novice, there may be inaccuracies). Reference : "Mobile Operating System Principles and Practice" Off Dongsheng, Android developer documentation: https://developer.android.google.cn/guide/components/activities/intro-activities?hl=zh_cn

Create Event

Creating an Activity requires two steps:
(1) preparation of the corresponding Activity class (java files).
(2) registered in the AndroidManifest.xml file.
First we create a project in Android Studio, open the file MainActivity.java here has helped us create a better Activity.

package com.beihang.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

At the same time need to be registered in the Manifest file: first need to declare Activity , as a child element of Application:

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

Here android: name = "..." is an essential element, the name of the Activity, this is can not easily change. If necessary, add some other properties, see the Android developer documentation can know.
Followed by even declare intent filters (the Intent-filter) , Android in the Intent-filter is a powerful feature, it makes Android the Activity can not only be invoked explicitly, implicitly also can start, for example: you can tell Android system, the completion of a job can find any of Activity to start, but do not specify which Activity.

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
        <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>

Child outset intent-filter element, the child element generally comprises a sub-action and an optional label category and sub-label data, the combined statement which is intended to accept Activity ** (Intent) **, by matching the filter intention to call this Activity. Tag of the three code illustrate: action tag indicating that the information can be transmitted Activity; category label instructions Activity can receive the activation request; data tag specifies the type of this data can be transmitted Activity. Specifically, how to start Activity will be mentioned below by intent.
We've created Activity and After registering in the Manifest file, you can implement your own logic in an Activity.

Life cycle activities

A Activity in its life cycle will go through multiple states. You can use a series of callbacks to handle transitions between states. First, a block diagram of dishing cycle Activity Statement:
Here Insert Picture Description
Direct use of the herein AndroidAPI FIG.
First activities are mainly three states: running, paused stopped . The correspondence relationship are: operating state is brought to the foreground activity at the top has, in this case active operating state (onResume), active operating state of focus can be obtained, to highlight this activity display; pause state is brought to the foreground when other activities the current activities are no longer top of the stack, still visible but dimmed, when activity in the suspended state (onPause), can not focus, recycling activities will be suspended state of the system memory is low; stopped when the activity is no longer in stack, is completely covered by other events, is stopped (onStop) is not visible, active member variable value at that time is still preserved, low recovery system memory.
See block diagram can be seen, when a start Activity, which onCreate (), onStart () and onResume () method is called, into the active operating state, when the other activities into the front (top of the stack) of the Activity of the onPause () method is called , as calling onCreate (), onStart () and onResume () to run the state into the active state of pause, kill the process if other applications require memory, back to the time and activities and start again; when activity is no longer visible, its onStop () method is called, the activity comes to a halt, halt status can still be invoked when the user onRestart wake () method to restart, kill the process in a time of low system memory.
Difference can write the following piece of code to test the Android phone's Back button and Home button.
Note that the onCreate () method,It Activity in the whole life cycle is executed only once, so some start-related logic need to write here

package com.beihang.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate");
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
    }
    
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "onRestart");
    }
}

Here we print out the information in each callback method call activity in, you can view real-time operational status of the Activity in the Logcat. Actual operation: App startup, print display onCreate (), onStart () and onResume () method is called; press the home button to print the contents of the display onPause () and onStop () method is called, the activity comes to a halt ; when you press the Back key, onPause (), onStop () and onDestroy () method is called, the system is destroyed activity. We will see clearly a callback acoustic Activity lifecycle and state switching method in the different. We only need to write our logic in the appropriate callback method on the line. More specific and detailed content of Activity lifecycle see the official documentation.

Conversion between different Activity

Most projects are not only a Activity, we need to jump in a different Activity. One activity into another activity in two ways: startActivity () and startActivityForResult (), both methods require passing an Intent object, the following were introduced:
(1) startActivity ()
If you do not need to return the newly launched Activity results , the current Activity can start it by calling startActivity () method.

Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);

Here we create an Intent object, wherein the second parameter is specific constructor component class names, you can specify a need to start Activity by this parameter, and then passed directly startActivity () method it is possible to jump to the SignInActivity. Intent on the back of content have time to write one.
Sometimes also desirable to pass some of this data to the next Activity Activity, for example, sending an email, SMS. This is accomplished through the exchange of data Intent object.

Intent intent = new Intent(this, SignInActivity.class);
intent.putExtra("userId", txtUserid.getText().toString());
startActivity(intent);

Intent object herein by putExtra () method passing a key - value pair, and then can acquire the data intended to be activated in SignInActivity.

Intent it = this.getIntent();
Bundle bundle = it.getExtras();
String userId = bundle.getString("userId");

(2) startActivityForResult ()
Sometimes you will want to get from Activity at the end of Activity results are returned. For example, you can start an Activity, allowing users to select a person in the contact list; when the end of the Activity, the system returns the user to select people. This time you can call startActivityForResult (Intent intent, int requestCode) method. The first parameter is the same as above Intent object startActivity () method, the second integer parameter is coded request, typically used to disambiguate between multiple times from the same startActivityForResult Activity of (Intent, int) call. Also, overwriting onActivityResult (int requestCode, int resultCode, Intent) method for the callback at the end of a child Activity, get children Activity data transmitted in this way.
Need to call setResult (int resultCode, Intent it) at the end of the event is for children Activity. for example:

btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(this, SuccessActivity.class);
                startActivityForResult(it, 123);
            }
        });
...
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent it) {
        if (requestCode == 123) {
            if (resultCode == 4) {
                Log.v(TAG, resultCode + "received");
            }
        }
    }

Activity in the child to be called setResult (int resultCode, Intent it) method:

btnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(4, (new Intent()).putExtra("userId", userid));
                this.finish();
            }
        });

So that when the child returns activities, the callback method onActivityResult () is invoked, and perform related operations.

to sum up

The film focused on activities (Activity) a brief description, and other advanced usage details see Android developer documentation. Articles divided into two methods to jump between Activity of creation, life cycle of different Activity. Activity Android project is a very important component in different states in different callback method to figure out running calls to be able to more clearly understand the program execution. The paper also involved in a number of concept intent (Intent), and will have time to write an article on the Intent.

Released eight original articles · won praise 3 · Views 2695

Guess you like

Origin blog.csdn.net/qq_41241926/article/details/104872988