Handler 异步消息处理

更新UI的操作必须在主线程中操作,若是在非主线程更新UI会报错:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

原因:在非主线程更新了UI,如下:

Handler 异步消息处理_第1张图片

解决方案:handler异步线程

package com.tzbc.databindtest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

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

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "tzbc";
    private static final int MSG_UPDATE = 415;

    private Button button;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == MSG_UPDATE){
                button.setText("new Thread");
            }
        }
    };

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

        button = findViewById(R.id.btUpdate);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(MSG_UPDATE);
            }
        });
    }


}

当有其他内容需要一起携带时,声明一个message:

Handler 异步消息处理_第2张图片

package com.tzbc.databindtest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

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

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "tzbc";
    private static final int MSG_UPDATE = 415;

    private Button button;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_UPDATE) {
                button.setText(msg.obj.toString());
            }
        }
    };

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

        button = findViewById(R.id.btUpdate);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String updateStr = "2020/04/15";
                Message message = Message.obtain();
                message.what = MSG_UPDATE;
                message.obj = updateStr;
                handler.sendMessage(message);
            }
        });
    }


}

 

你可能感兴趣的