Android之Handler消息处理
程序员文章站
2022-03-08 11:54:44
...
主要用途
- 未来某时做某事
- 线程间通信
package com.example.test0508;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.example.test0508.util.ToastUtil;
public class HandlerActivity extends AppCompatActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
//直观的线程通信
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
ToastUtil.showMessage(HandlerActivity.this,"线程通信成功");
break;
}
}
};
//延时五秒后跳转到另一个activity
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(HandlerActivity.this,EventActivity.class);
startActivity(intent);
}
}, 5000);
new Thread(){
@Override
public void run() {
super.run();
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
}.start();
}
}
布局文件随便写