[Multithreading, UI update and asynchronous processing mechanism] Thread integration notes

1. Basic three threading methods

1. [Inheritance method, high coupling] Define a thread: create a new class inherited from Thread, and rewrite the run method of the parent class

Insert picture description here
2. Create a new instance object and execute thread run operation through start()
Insert picture description here

2. [Implementing interface method]: To implement the Runnable interface, pass the implemented interface object of new when calling, and then pass it to the Thread construction method and start again.

Insert picture description here

3. Anonymous method

Insert picture description here

  1. Just open Kotlin directly
    Insert picture description here

2. Thread and update UI

1. Introduction to asynchronous message processing mechanism:

  1. Message (delivered message)
  2. Handler (handler, sending and processing messages)
  3. MessageQueue (the message queue stores messages)
  4. Looper (the message loop in the execution thread, after calling Looper's loop() method, it will enter an infinite loop, and every time a message is found in the Queue, it will be taken out)

2. Use Handler to send handleMessage from child thread back to main thread, using anonymous inner class

    private Handler handler = new Handler() {
    
    

        public void handleMessage(Message msg) {
    
    
            switch (msg.what) {
    
    
                case UPDATE_TEXT:
                    // 在这里可以进行UI操作
                    text.setText("Nice to meet you");
                    break;
                default:
                    break;
            }
        }

    };
                new Thread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message); // 将Message对象发送出去
                    }
                }).start();

3. Create a new Handler method in the child thread [otherwise it will report an error]

Insert picture description here

3. Use AsyncTask [abstract class needs to be inherited]

Insert picture description here
Insert picture description here
Insert picture description here

//启动任务:
	new DownloadTask().execute()
 
	//新建类继承AsyncTask:
	class DownloadTask extends AsyncTask<Void, Integer, Boolean> {
    
    //不需要传参给后台任务,进度显示单位为int,使用boolean来反馈执行结果
		
		protected void onPreExecute() {
    
    
			progressDialog.show(); // 显示进度对话框
		}
		
		@Override
		protected Boolean doInBackground(Void... params) {
    
    
			try {
    
    
				while (true) {
    
    
					int downloadPercent = doDownload(); // 这是一个虚构的方法
					publishProgress(downloadPercent);
					if (downloadPercent >= 100) {
    
    
						break;
					}
				}
			} catch (Exception e) {
    
    
				return false;
			}
			return true;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
    
    
			// 在这里更新下载进度
			progressDialog.setMessage("Downloaded " + values[0] + "%");
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
    
    
			progressDialog.dismiss(); // 关闭进度对话框
			// 在这里提示下载结果
			if (result) {
    
    
				Toast.makeText(context, "Download succeeded",Toast.LENGTH_SHORT)
.show();
			} else {
    
    
				Toast.makeText(context, " Download failed",	Toast.LENGTH_SHORT).show();
			}
		}
	}

Four. Delay messages through postDelayed

1. The View control performs [Post delay, which is in the main thread]

  1. Example 1
    Insert picture description here
  2. Example 2
Handler().postDelayed(Runnable {
    
     rotateAnimation!!.start() }, 2000)

2.handler delay

  1. The handler method has two methods: send and post.
    1) The commonly used send method is to call the sendMessage (message) of the handler after the time-consuming operation is processed in the worker thread to send the message object to the main thread. Write the handlerMessage() method,
    2) The post method passes a runnable object, and the operation of updating the UI is also performed in the run method of this runnable, that is to say, the code in the run method is executed in the main thread, although It is written in the worker thread, and the main thread automatically executes the code in the run method of runnable after receiving the message. )
    The send and post the source code
    annotations
    Insert picture description here
    Insert picture description here
    Insert picture description here
    t

5. Use runOnUiThread to judge and switch the main thread for toast thread processing

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38304672/article/details/112406941