Android 中的 Handler 消息处理
主要用途:
- 未来某时做某事.
- 线程间通信.
package com.example.hello;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.example.hello.util.ToastUtil;
public class HandlerActivity extends AppCompatActivity {
private Handler handler;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
handler = new Handler();
// 3 秒后执行
handler.postDelayed(() -> {
Intent intent = new Intent(HandlerActivity.this, ButtonActivity.class);
startActivity(intent);
}, 3000);
handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
ToastUtil.showShortToast(HandlerActivity.this, "1 线程通信成功");
break;
default:
throw new IllegalStateException("Unexpected value: " + msg.what);
}
}
};
new Thread() {
@Override
public void run() {
super.run();
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}.start();
}
}