AndroidActivity

Activity

  • Activity is a display component, which is mainly used to implement application function logic and display data or receive user input through the interface.
  • An application can contain zero or more activities. Without an active application, the user will not be able to see the program interface. Such applications usually run in the background and do not involve user interaction.

Basic operations of activities

  • Bind a custom view to the activity: setContentView(R.layout.activity_main);
  • Start another activity: startActivity(intent);
  • End activity: finish();

Example 1: App with page jump function

The specific results are as shown in the figure

  • Create a new ActivityWork project

  • Create a second Activity file

  • Create a new button on each of the two interfaces, as shown in the figure:

  • Edit the two Java programs in the picture above respectively. The specific codes are as follows:
 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7
 8 public class MainActivity extends AppCompatActivity {
 9 private Button button;
10
11 @Override
12 protected void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 setContentView(R.layout.activity_main);
15
16 button = (Button)findViewById(R.id.button);
17
18 button.setOnClickListener(new View.OnClickListener() {
19 @Override
20 public void onClick(View v) {
21 Intent intent = new Intent(MainActivity.this,Main2Activity.class);
22 startActivity(intent);
twenty three             }
twenty four         });
25}
26}

MainActivity.java

 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.os.Bundle;
 4 import android.view.View;
 5 import android.widget.Button;
 6
 7 public class Main2Activity extends AppCompatActivity {
 8 private Button button2;
 9 
10 @Override
11 protected void onCreate(Bundle savedInstanceState) {
12 super.onCreate(savedInstanceState);
13 setContentView(R.layout.activity_main2);
14
15 button2 = (Button)findViewById(R.id.button2);
16 button2.setOnClickListener(new View.OnClickListener() {
17 @Override
18 public void onClick(View v) {
19 finish();
20}
twenty one         });
twenty two     }
23}

Main2Activity.java

  • After running, as shown in the picture above! ! !

Activity life cycle

  • The life cycle of Activity refers to the entire process from creation to destruction of Activity. During a life cycle, Activity may exist in multiple states. An in-depth understanding of the Activity life cycle will help you manage application resources more rationally and design more efficient applications.

  • Activity life cycle includes creation, visibility, focus acquisition, loss of focus, invisible, re-visibility, destruction, etc. Each link of Activity defines relevant callback methods, as follows:
Name Calling time
onCreate(Bundle savedInstanceState) Activity creation When called, it usually does some initialization settings.
onStart() Called when the Activity becomes visible to the user on the screen.
onResume() Called when Activity gets focus.
onPause() Called when the current activity is covered by other activities or the screen is locked.
onStop() Called when the Activity is not visible to the user.
onRestart() Called when restarting a stopped Activity.
onDestroy() Called when the Activity is destroyed.
This method may be called because someone directly calls the finish() method or the system decides to stop the activity to free up resources.
  • The calling process of methods in the Activity life cycle is shown in the figure. You can intuitively understand the entire life cycle of the Activity.

  • The life cycle of Activity is expressed at three levels, as shown in the figure, which can provide a clearer understanding of the operating mechanism of Activity.

  • If the Activity leaves the visible phase and loses focus for a long time, it is likely to be destroyed by the system to release resources. Of course, even if the Activity is destroyed, the changes made by the user to the Activity will be saved in the Bundle object. When the user needs to redisplay the Activity, the Android system will rebuild the Activity based on the previously saved user change information.

Activity data transfer

  • Pass data using putExtra()
  • The putExtra(name, value) method can encapsulate the specified data into the Intent object. Among them, name is a string representing the name of the data, and value is the value of various data types to be transferred.
  • To obtain the data encapsulated in the Intent object, various getXXXExtra() methods can be called.

1. Use Inten’s putExtra to pass

Name Calling time
getCharExtra(Stringname,chardefaultValue) Get the char type data of the specified name.
getFloatExtra(Stringname, floatdefaultValue) Get the float type data of the specified name.
getFloatArrayExtra(Stringname) Get the float type array of the specified name.
getlntArrayExtra(Stringname) Get the int type array of the specified name.
getlntExtra(Stringname,intdefaultValue) Get the int type data of the specified name.
getStringArrayExtra(Stringname) Get the String type array of the specified name.
getstringExtra(Stringname) Get the String type data of the specified name.
getSerializableExtra(Stringname) Get the object data of the specified name.
  • These are two XML files that implement data transmission and acceptance interfaces

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <androidx.constraintlayout.widget.ConstraintLayout
 3 xmlns:android="http://schemas.android.com/apk/res/android"
 4 xmlns:app="http://schemas.android.com/apk/res-auto"
 5 xmlns:tools="http://schemas.android.com/tools"
 6 android:layout_width="match_parent"
 7 android:layout_height="match_parent"
 8 tools:context=".MainActivity">
 9 
10<Button
11 android:id="@ + id/button"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginStart="41dp"
15 android:layout_marginTop="34dp"
16 android:text="Jump"
17 app:layout_constraintStart_toStartOf="parent"
18 app:layout_constraintTop_toTopOf="parent" />
19
20 </androidx.constraintlayout.widget.ConstraintLayout>

activity_main2.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <androidx.constraintlayout.widget.ConstraintLayout
 3 xmlns:android="http://schemas.android.com/apk/res/android"
 4 xmlns:app="http://schemas.android.com/apk/res-auto"
 5 xmlns:tools="http://schemas.android.com/tools"
 6 android:layout_width="match_parent"
 7 android:layout_height="match_parent"
 8 tools:context=".Main2Activity">
 9 
10 <TextView
11 android:id="@ + id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginTop="84dp"
15 android:text="TextView"
16 android:textSize="30sp"
17 app:layout_constraintStart_toStartOf="parent"
18 app:layout_constraintTop_toTopOf="parent" />
19 </androidx.constraintlayout.widget.ConstraintLayout>
  • Two Java files

MainActivity.java

 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7
 8 public class MainActivity extends AppCompatActivity {
 9 
10 private Button button;
11 @Override
12 protected void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 setContentView(R.layout.activity_main);
15
16 button = findViewById(R.id.button);
17 button.setOnClickListener(new View.OnClickListener() {
18 @Override
19 public void onClick(View v) {
20 Intent intent = new Intent(MainActivity.this,Main2Activity.class);
21 //Use putExtra to pass data
22 intent.putExtra("name","zhangsan");
23 intent.putExtra("score",95);
twenty four 
25 startActivity(intent);
26}
27 });
28 }
29}

Main2Activity.java

 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.widget.TextView;
 6
 7 import androidx.appcompat.app.AppCompatActivity;
 8 
 9 public class Main2Activity extends AppCompatActivity {
10
11 private TextView textView;
12
13 @Override
14 protected void onCreate(Bundle savedInstanceState) {
15 super.onCreate(savedInstanceState);
16 setContentView(R.layout.activity_main2);
17
18 Intent intent = getIntent();
19
20 //Use getExtra to receive data
21 String name = intent.getStringExtra("name");
22 int score = intent.getIntExtra("score", 0);
twenty three 
24 textView = findViewById(R.id.textView);
25 textView.setText("name=" + name + ",score=" + score);
26}
27}
  • The implementation is as shown in the figure:

2. Use Intention’s Bundle delivery

  • Encapsulate various data into a Bundle object, and then encapsulate the Bundle object into an Intent object and pass it to the started activity.
  • The various putXXX(String key, XXX value) methods of the Bundle object can encapsulate XXX type data into it, and the corresponding getXXX(String key) method can be used to obtain data from it.
  • After the Bundle object is ready, call the putExtras(bundle) or putExtra(name, bundle) method to encapsulate it into the Intent object.
  • When you want to obtain the Bundle object from the Intent object, just call the corresponding getExtras() or getBundleExtra() method.

The operation steps are similar to puttingExtra() to pass data. You only need to change two Java files among the four files above. The specific code is as follows:

MainActivity.java

 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7
 8 public class MainActivity extends AppCompatActivity {
 9 
10 private Button button;
11 @Override
12 protected void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 setContentView(R.layout.activity_main);
15
16 button = findViewById(R.id.button);
17 button.setOnClickListener(new View.OnClickListener() {
18 @Override
19 public void onClick(View v) {
20 Intent intent = new Intent(MainActivity.this,Main2Activity.class);
twenty one 
22 //Use Bundle to transfer data
23 Bundle bundle = new Bundle();
24 bundle.putString("name","zhangsan");
25 bundle.putInt("score",95);
26 intent.putExtras(bundle);
27
28 startActivity(intent);
29 }
30 });
31}
32}

Main2Activity.java

 1 import androidx.appcompat.app.AppCompatActivity;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.widget.TextView;
 6
 7 import androidx.appcompat.app.AppCompatActivity;
 8 
 9 public class Main2Activity extends AppCompatActivity {
10
11 private TextView textView;
12
13 @Override
14 protected void onCreate(Bundle savedInstanceState) {
15 super.onCreate(savedInstanceState);
16 setContentView(R.layout.activity_main2);
17
18 Intent intent = getIntent();
19
20 //Use Bundle to receive data
21 Bundle bundle = intent.getExtras();
22 String name = bundle.getString("name");
23 int score = bundle.getInt("score",0);
twenty four 
25 textView = findViewById(R.id.textView);
26 textView.setText("name=" + name + ",score=" + score);
27}
28}
  • The running display is as follows:

  • The following types will not be described in detail, only the code will be provided.

3. Use static variables to pass data

First Activity

1 Intent intent = new Intent(MainActivity.this,TwoActivity.class);
2 TwoActivity.name="Awesome";
3 TwoActivity.str="You said";
4 startActivity(intent);

Second Activity

1 //static variable
2 protected static String name;
3 protected static String str;
4 tv.setText(str + name);

4. Use serialization object Seriazable

Tools

 1 import java.io.Serializable;
 2 class DataBean implements Serializable {
 3 private String name;
 4 private string sex;
 5 public String getName() {
 6 return name;
 7}
 8 public void setName(String name) {
 9 this.name = name;
10}
11 public String getSex() {
12 return sex;
13}
14 public void setSex(String sex) {
15 this.sex = sex;
16}
17}

First Activity

1 //Create intent
2 Intent intent = new Intent(MainActivity.this,TwoActivity.class);
3 DataBean bean = new DataBean();
4 //Save data into the DataBean object through the set method
5 bean.setName("LaLa");
6 bean.setSex("male");
7 intent.putExtra("key", bean);
8 startActivity(intent);

Second Activity

1 Intent intent = getIntent();
2 //Deserialize data object
3 Serializable se = intent.getSerializableExtra("key");
4 if(se instanceof DataBean){
5 //Get the DataBean object db carrying data
6 DataBean db = (DataBean) se;
7 tv.setText(db.getName() + "===" + db.getSex());
8}

5. SharedPreferences transfer data

In the first Activity

1 SharedPreferences sp = this.getSharedPreferences("info", 1);
2 //Get the sp editor
3 Editor edit = sp.edit();
4 edit.putString("data", str);
5 edit.commit();
6 //Create intent object
7 Intent intent = new Intent(MainActivity.this,TwoActivity.class);
8 //Activate intent
9 startActivity(intent);

In the second Activity

SharedPreferences sp = this.getSharedPreferences("info", 1);
//Set data
tv.setText(sp.getString("data", ""));

6. Pass data when destroying using Activity

In the first Activity

1 Intent intent = new Intent(MainActivity.this,TwoActivity.class);
2 //Start Activity in a special way
3 startActivityForResult(intent, 11);
4 //Set data
5 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
6 super.onActivityResult(requestCode, resultCode, data);
7 String str = data.getStringExtra("data");
8 tvOne.setText(str);
9}

In the second activity

1 //Set the returned data
2 Intent intent = new Intent();
3 intent.putExtra("data", edtOne.getText().toString().trim());
4 setResult(3, intent);
5 //Close the current activity
6 finish();

7. Get the data returned by the activity

  • startActivityForResult(intent, requestCode) method to start the activity, the request returns the result:
    • The parameter intent is an Intent object used to encapsulate the data that needs to be passed to the activity;
    • The parameter requestCode is the request code, which is an integer used to identify the current request; an activity may receive requests from other different activities, and when returning from the activity, it will return the received request code as it is;
    • When processing the return result, you can use the request code to determine whether it is returned from the requested activity.
    • In the second Activity, use the setResult(resultCode, intent) method to set the return result resultCode to the result code, and intent is the Intent object that encapsulates the return data.

    • ntent data) method to process the returned results:

      • requestCode is the request code it received returned from the requested activity;

      • data is the Intent object returned by the request activity, from which the returned data can be obtained.

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <androidx.constraintlayout.widget.ConstraintLayout
 3 xmlns:android="http://schemas.android.com/apk/res/android"
 4 xmlns:app="http://schemas.android.com/apk/res-auto"
 5 xmlns:tools="http://schemas.android.com/tools"
 6 android:layout_width="match_parent"
 7 android:layout_height="match_parent"
 8 tools:context=".MainActivity">
 9 
10 <TextView
11 android:id="@ + id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="Hello World!"
15 app:layout_constraintBottom_toBottomOf="parent"
16 app:layout_constraintLeft_toLeftOf="parent"
17 app:layout_constraintRight_toRightOf="parent"
18 app:layout_constraintTop_toTopOf="parent" />
19
20<Button
21 android:id="@ + id/button"
22 android:layout_width="wrap_content"
23 android:layout_height="wrap_content"
24 android:layout_marginStart="70dp"
25 android:layout_marginLeft="70dp"
26 android:layout_marginTop="90dp"
27 android:text="Button"
28 app:layout_constraintStart_toStartOf="parent"
29 app:layout_constraintTop_toTopOf="parent" />
30
31 </androidx.constraintlayout.widget.ConstraintLayout>

activity_main2.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <androidx.constraintlayout.widget.ConstraintLayout
 3 xmlns:android="http://schemas.android.com/apk/res/android"
 4 xmlns:app="http://schemas.android.com/apk/res-auto"
 5 xmlns:tools="http://schemas.android.com/tools"
 6 android:layout_width="match_parent"
 7 android:layout_height="match_parent"
 8 tools:context=".Main2Activity">
 9 
10<Button
11 android:id="@ + id/button2"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginStart="82dp"
15 android:layout_marginLeft="82dp"
16 android:layout_marginTop="153dp"
17 android:text="Button"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent" />
20 </androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

 1 import android.content.Intent;
 2 import android.os.Bundle;
 3 import android.view.View;
 4 import android.widget.Button;
 5 import android.widget.TextView;
 6
 7 import androidx.annotation.Nullable;
 8 import androidx.appcompat.app.AppCompatActivity;
 9 
10/**
11 * Clicking the Button will jump from the first interface to the second interface. Clicking the Button on the second interface will jump back to the first interface and return the data to the first interface.
12 */
13 public class MainActivity extends AppCompatActivity {
14
15 private Button button;
16 private TextView textView;
17
18 @Override
19 protected void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.activity_main);
twenty two 
23 textView = findViewById(R.id.textView);
twenty four 
25 button = findViewById(R.id.button);
26 button.setOnClickListener(new View.OnClickListener() {
27 @Override
28 public void onClick(View v) {
29 Intent intent = new Intent(MainActivity.this, Main2Activity.class);
30 //Request return result
31 startActivityForResult(intent, 1);
32}
33 });
34}
35
36/**
37 * Return result processing
38*
39 * @param requestCode
40 * @param resultCode
41 * @param data
42 */
43 @Override
44 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
45 super.onActivityResult(requestCode, resultCode, data);
46 if (requestCode == 1) {
47 if (resultCode == 1) {
48 //Get the returned result
49 String string = data.getStringExtra("ExtraData");
50 //Set the return result to textView
51 textView.setText(string);
52 }
53}
54
55 }
56}

Main2Activity.java

 1 import android.content.Intent;
 2 import android.os.Bundle;
 3 import android.view.View;
 4 import android.widget.Button;
 5
 6 import androidx.appcompat.app.AppCompatActivity;
 7
 8 public class Main2Activity extends AppCompatActivity {
 9 
10 private Button button2;
11
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_main2);
16
17 button2 = findViewById(R.id.button2);
18 button2.setOnClickListener(new View.OnClickListener() {
19 @Override
20 public void onClick(View v) {
21 Intent intent = new Intent();
22 intent.putExtra("ExtraData", "Data from the second interface");
23 //Set the return result and return the value of "ExtraData" through the intent
24 setResult(1, intent);
25 finish();
26}
27 });
28 }
29}
  • The operation is as shown in the figure:

  • That’s all about Android Activity. If you have any questions, please leave a message! ! !
  • Quote reference 1: Complete data communication methods between Android activities (1)
  • Reference 2: Summary of Android’s five data transfer methods
  • Quote reference 3: About 6 ways to transfer data between Android activities