Activity - Android

1. What is the activity

An activity is a component that can contain a user interface and is mainly used to interact with users. An application can contain zero or more activities, but applications that do not contain any activities are rare.

2. Basic usage of activities

2.1. Create activities

public class MainActivity extends AppCompatActivity {

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

2.2. Creating and loading layouts

first_layut.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="Button 1"
        />
</LinearLayout>

2.3 Activity Registration

All activities need to be registered in AndroidManifest.xml to take effect, and Android Studio will register automatically

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zc.app2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication1">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

2.4. Use Toast in activities

Toast is a very good reminder provided by the Android system. It can be used in the program to notify users of some short information. These information will disappear automatically after a period of time and will not occupy any screen space

Toast usage

The usage of Toast is very simple. Create a Toast object by static method makeText(), then call show() to display Toast. Note that the makeText() method needs to pass in three parameters. The first parameter is Context, which is the Context required by toast. Since the activity itself is a Context object, you can directly pass in FirstActivity.this here. The second parameter is the text content displayed by toast. The third parameter is the duration displayed by toast. Toast.length can be selected as two built-in constants_ Short and Toast.LENGTH_LONG.

Define a trigger point for pop-up Toast

Click the definition button to pop up

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layut);
        Button button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Toast.makeText(FirstActivity.this,"You clicked Button 1",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

2.5. Use Menu in activities

New menu folder

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:id="@+id/add_item"
        android:title="Add"/>
    <item 
        android:id="@+id/remove_item"
        android:title="Remove"/>
</menu>

Override the onCreateOptionsMenu method in FirstActivity

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;

    }

Define menu response events

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_item:
                Toast.makeText(this,"You clicked Add",Toast.LENGTH_SHORT).show();
                break; 
            case R.id.remove_item:
                Toast.makeText(this,"You clicked Remove",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }



2.6 destruction of an activity

Press the Back key or use the finish() method to destroy the activity

Modify the code in the listener

        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });

3. Use Intent to shuttle between activities

3.1. Use explicit Intent

Create SecondActivity.java and second_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2"/>

</LinearLayout>

Intent has multiple constructor overloads, one of which is intent (Context packagecontext, class <? > class). This constructor receives two parameters. The first parameter, Context, requires a Context to start the Activity, and the second parameter, class, specifies the target Activity to start. Through this constructor, the "intention" of intent can be constructed. Then how should we use this intent? The Activity class provides a startActivity() method, which is specially used to start the Activity. It receives an intent parameter. Here, we pass the constructed intent into the startActivity() method to start the target Activity.

Modify the click of the button in FirstActivity
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
Run the program and click the button

Use implicit Intent

Compared with explicit Intent, implicit Intent is much more implicit. It does not specify which activity we want to start, but specifies a series of more abstract information such as action and category, and then the system analyzes the Intent and helps us find out the appropriate activity to start.

Modify AndroidManifest.xml
        <activity android:name=".SecondActivity"
            android:exported="false">
            <intent-filter>
                <action android:name="com.zc.app2.ACTION_START"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
Modify the button click event of FirstActivity
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.zc.app2.ACTION_START");
                startActivity(intent);
            }
        });

Pass data to the next activity

intent.putExtra temporarily stores the transferred data in intent
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String data = "Hello SecondActivity";
                Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
                intent.putExtra("extra_data",data);
                startActivity(intent);
            }
        });

receive data
public class SecondActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.second_layout);
       Intent intent = getIntent();
       String data = intent.getStringExtra("extra_data");
       Log.d("SecondActivity",data);
   }
}

Returns data to the previous activity

        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
                startActivityForResult(intent,1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        switch (requestCode) {
            case 1:
                if (requestCode == RESULT_OK) {
                    String returnData = data.getStringExtra("data_return");
                    Log.d("FirstActivity", returnData);
                }
                break;

            default:
        }

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("data_return","Hello FirestActivity");
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }

4. Declaration cycle of the activity

Return stack

Android uses tasks to manage activities. A task is a collection of activities stored in the stack, which is also called the Back Stack Stack is a last in, first out data structure. By default, whenever we start a new activity, it will be pushed into the stack in the return stack and at the top of the stack. Whenever we press the Back key or call finish() Method to destroy an activity, the activity at the top of the stack will be out of the stack, and the previous activity on the stack will be at the top of the stack again. The system will always display the activity at the top of the stack to the user.

Active state

1. Operation status
When an activity is at the top of the return stack, it is in the running state. The last thing the system wants to recycle is the running activity, because it will bring a very poor user experience.

2. Suspended status
When an activity is no longer at the top of the stack but is still visible, the activity enters a pause state. You may think that since the activity is no longer at the top of the stack, how can it be visible? This is because not every activity will occupy the whole screen. For example, an activity in the form of dialog box will only occupy part of the middle area of the screen. You will see this in the back soon A suspended activity is still completely alive, and the system is unwilling to recycle this activity (because it is still visible, recycling visible things will have a bad impact on the user experience). The system will consider recycling this activity only when the memory is very low.
3. Stop status
When an activity is no longer at the top of the stack and is completely invisible, it enters the stop state. The system will still save the corresponding state and member variables for this activity, but this is not completely reliable. When memory is needed elsewhere, activities in the stop state may be recycled by the system.
4. Destruction status
When an activity is removed from the return stack, it becomes destroyed. The system will most tend to recycle the activities in this state, so as to ensure that the phone has enough memory.

Activity lifetime

Seven callback methods are defined in the Activity class, covering every link of the Activity life cycle.

oncreate()

In each activity, we have rewritten this method, which will be called when the activity is created for the first time. You should complete the initialization of the activity in this method, such as loading layout, binding events, etc.

onStart()

This method is called when the activity changes from invisible to visible.

onResume()

This method is called when the activity is ready to interact with the user. At this time, the activity must be at the top of the return stack and in running state.

onPause()

This method is called when the system is ready to start or resume another activity. Usually, some CPU consuming resources will be released and some key data will be saved in this method, but the execution speed of this method must be fast, otherwise it will affect the use of new stack top activities.

onStop()

This method is called when the activity is completely invisible. The main difference between this method and onPause() method is that if the new activity started is a dialog activity, onPause() method will be executed, while onStop() method will not be executed.

onDestroy()

This method is called before the activity is destroyed, and then the state of the activity will be destroyed.

onRestart()

This method is called before the activity changes from stop state to running state, that is, the activity is restarted.

Among the above seven methods, except onRestart() method, the others are relative, so the activities can be divided into three survival periods.

Complete survival

What an activity goes through between the oncreate() method and the onDestroy() method is the full lifetime. Generally, an activity will complete various initialization operations in the oncreate() method and free memory in the onDestroy() method.

Visible survival

What an activity goes through between the onStart() method and the onStop() method is the visible lifetime. During the visible lifetime, activities are always visible to users, even if they may not be able to interact with users. Through these two methods, we can reasonably manage the resources visible to users. For example, resources are loaded in the onStart() method and released in the onStop() method to ensure that activities in the stopped state do not occupy too much memory.

Foreground lifetime

What an activity goes through between the onResume() method and the onPause() method is the foreground lifetime. During the lifetime of the foreground, activities are always running. At this time, activities can interact with users. We usually see and contact the most activities in this state.

Active startup mode

  1. standard
  2. singleTop
  3. singleTask
  4. singleInstance

standard

The default startup mode is that whenever a new activity is started, it will be put on the return stack and at the top of the stack. For an activity in standard mode, the system does not care whether the activity already exists in the return stack. A new instance of the activity will be created every time it is started.

singleTop

When the startup mode of an activity is specified as singTop, when starting an activity, if it is found that the top of the returned stack is already the activity, it is considered that it can be used directly and no new activity instance will be created.

singleTask

When the startup mode of an activity is specified as singleTask, each time the activity is started, the system will first check whether there is an instance of the activity in the return stack. If it already exists, the instance will be used directly, and all activities above the activity will be out of the stack. If not, a new activity instance will be created.

singleInstance

singleInstance mode should be the most special and complex of the four startup modes. You also need to spend more time to understand this mode. Different from the above three startup modes, the activity specified as singleInstance mode will enable a new return stack to manage the activity (if the singleTask mode specifies different taskAffinity, a new return stack will also be started). Suppose an activity in our program is allowed to be called by other programs. If we want to realize that other programs and our programs can share the instance of this activity, we can solve this problem by using the singleInstance mode. In this mode, there will be a separate return stack to manage this activity, no matter which application accesses the activity, All share the same return stack, which solves the problem of sharing activity instances.

Tags: Java Android Android Studio

Posted on Thu, 02 Dec 2021 13:55:45 -0500 by popcop