Android multithreaded programming

Basic usage of threads:

Android multi-threaded programming is actually no more special than java multi-threaded programming. Basically, the same usage is used. For example, to define a thread, you only need to create a new class to inherit Thread, then rewrite the run method of the parent class, and write time-consuming logic in it, as shown below:

class MyThread extends Thread{
    
    
	@Override
	public void run(){
    
    
	//处理具体的逻辑
	}
}

So how to start this thread? In fact, it is very simple. You only need to create a new instance of MyThread, and then call its start() method, so that the code in the run() method will run in the child thread, as shown below:

Of course, the use of inheritance is a bit highly coupled, and more often we will choose to use the Runnable interface to define a thread, as shown below:

class MyThread implements Runnable{
    
    
	@Override
	public void run(){
    
    
	//处理具体的逻辑
	}
}

If this writing method is used, the method of starting the thread also needs to be changed accordingly, as shown below

MyThread mythread = new MyThread();
new Thread(myThread).start();

The constructor of Thread receives a Runnable parameter, and our new MyThread is an object that implements the Runnable interface and passes it to the constructor of Thread.

Update the UI in the child thread

Android's UI thread is also unsafe. If you want to update UI elements in the application, you must do it in the main thread, otherwise an exception will occur.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/change_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change Text"
        android:textAllCaps="false"
        />
    <TextView
        android:id="@+id/ch_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World"
        android:textSize="20sp"
        />


</RelativeLayout>

MainActivity.java

package net.nyist.lenovo.androidthreadtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
    

    private Button mBtnChangeView;
    private TextView tvText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnChangeView = (Button) findViewById(R.id.change_text);
        tvText = (TextView) findViewById(R.id.ch_text);
        mBtnChangeView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.change_text:
                new Thread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        tvText.setText("Nice to meet you!");
                    }
                }).start();
                break;
            default:
                break;
        }
    }
}

We only have a button and a textView, a sub-thread is started in the button click event, and then the setText() method of TextView is called in the sub-thread to display the string as Nice to meet you. The code is very simple, but an error occurs when it runs. Mine is a test with a real machine and a crash occurs after clicking the button.
Write picture description here
This proves that Android does not allow UI operations in child threads. But if you want to perform some time-consuming tasks in the child thread, then update the corresponding UI controls according to the execution result of the task. For these Androids, provide a set of asynchronous message processing mechanism, which perfectly solves the UI in the child thread. Operational problems.

Modify the code in MainActicity

package net.nyist.lenovo.androidthreadtest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
    

    private Button mBtnChangeView;
    private TextView tvText;
    public static final int UPDATE_TEXT = 1;
    private Handler handler = new Handler(){
    
    
        public void handleMessage(Message msg){
    
    
            switch (msg.what){
    
    
                case UPDATE_TEXT:
                    tvText.setText("Nice to meet you!");
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnChangeView = (Button) findViewById(R.id.change_text);
        tvText = (TextView) findViewById(R.id.ch_text);
        mBtnChangeView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.change_text:
                new Thread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message);   //将Message对象发出去
                    }
                }).start();
                break;
            default:
                break;
        }
    }
}

Write picture description here

Analysis of asynchronous message processing mechanism

Asynchronous message processing in Android is mainly composed of four parts: Message, Handler, MessageQueue and Looper.
1. Message
Message is a message passed between threads. It can carry a small amount of information internally and is used to exchange data between different threads. Above we used the what field of Message, in addition to arg1 and arg2. Field to carry some integer data, use the obj field to carry an Object object.
2. Handler
Handler, as the name suggests, is the meaning of the processor. It is mainly used to send and process messages. Sending messages generally uses the sendMessage() method of Handler. After a series of processing, the sent message will eventually be delivered. To the handleMessage() method of Handler.
3. MessageQueue
MessageQueue means message queue, it is mainly used to store all messages sent through Handler. This part of the message will always exist in the message queue, waiting to be processed. There will only be one MessageQueue object in each thread.
4. Looper
Looper is the steward of MessageQueue in each thread. After calling Looper's loop() method, it will enter an infinite loop, and then whenever a message is found in MessageQueue, it will be taken out and delivered To Hnadler's handleMessage() method. There will be only one Looper in each thread.

Asynchronous message processing flow:
1. First, create a Handler object in the main thread and rewrite the handlerMessage() method.

2. When UI operations are required in the child thread, a Message object is created and the message is sent out through the Handler.

3. After that, the message will be added to the MessageQueue queue to be processed, and Looper will always try to retrieve the pending message from the MessageQueue.

4. Finally distributed back to the handleMessage() method of the Handler.

Since the Handler is created in the main thread, the code in the handleMessage() method will also run in the main thread at this time, so we can safely perform UI operations here. The flow diagram of the entire asynchronous message processing mechanism is as follows The picture shows:

Write picture description here

Guess you like

Origin blog.csdn.net/i_nclude/article/details/77995716