先看一个使用Handler的简单实例:先不考虑Handler造成的内存泄漏问题
package cn.zzw.messenger.handlerdemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
private MyHandler mHandler;
private TextView mTv;
private Button mBtn;
private class MyHandler extends Handler {
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == 10086) {
mTv.setText(String.valueOf(msg.arg1));
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler();
mTv = findViewById(R.id.mTv);
mBtn = findViewById(R.id.mBtn);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread() {
@Override
public void run() {
try {
int i = 0;
while (i < 100) {
i++;
Thread.sleep(300);
Message msg = Message.obtain();
msg.what = 10086;
msg.arg1 = i;
mHandler.sendMessage(msg);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
});
}
}
步骤:
a. 创建 Handler 对象
b.创建Message对象,封装消息
c.调用 mHandler.sendMessage(msg) 从子线程发送消息
d.在Handler中重写 handleMessage(@NonNull Message msg) 方法,接收消息并处理消息。