android Handler

113 阅读1分钟

「这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战

为什么使用Handler?

先看一段代码

package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.st);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=5; i>0; i--){
                    textView.setText(""+i);
                    try{
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                startActivity(new Intent(MainActivity.this,MainActivity2.class));
            }
        }).start();
    }
}

这里想要新建一个线程来对UI来进行修改,但是这个UI在原来的线程当中. 而android 中只能为在原线程中对UI来进行修改,所以会报以下错误. 在这里插入图片描述 那么该怎么办呢? 可以通过Handler来修改.

用Handler来传递信息

我们可以在原线程中new 一个Handler 的匿名子类对象来接收新线程传来的''指令''和''参数'',从而在原线程中进行修改.

package com.example.test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    final static int update=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.st);
        Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case update :
                        textView.setText(""+msg.arg1);
                        break;
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=5; i>0; i--){
                    Message msg=new Message();
                    msg.what=update;
                    msg.arg1=i;
                    try{
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    handler.sendMessage(msg);
                }
                startActivity(new Intent(MainActivity.this,MainActivity2.class));
            }
        }).start();
    }
}

Handler实现原理

要实现Handler message: 传递的数据模型. Handler: 发送message和接收message messageQueue:消息队列,每个线程只有一个消息队列. Looper:负责将消息从队列回送Handler.一个线程只有一个Looper. 在这里插入图片描述