handler使用在哪些场景
发布网友
发布时间:2022-05-05 00:14
我来回答
共1个回答
热心网友
时间:2022-06-27 15:41
一、 应用场景一
1. 说明
某些不需要实时显示的,可以先放到消息队列中(例如弹出提示信息,更新UI等)
2. 示例代码
[java] view plain copy print?
// handler类接收数据
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == MOBILE_STATUS || msg.what == WIFI_STATUS) {
showNetMethod(msg.what);
System.out.println("receive....");
}
};
};
Message msg = new Message();
msg.what = WIFI_STATUS;
handler.sendMessage(msg);
// handler类接收数据
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == MOBILE_STATUS || msg.what == WIFI_STATUS) {
showNetMethod(msg.what);
System.out.println("receive....");
}
};
};
Message msg = new Message();
msg.what = WIFI_STATUS;
handler.sendMessage(msg);
二、 应用场景二
1. 说明
在一个子线程中去创建一个Handler,然后使用这个handler实例在任何其他线程中发送消息,最终处理消息的代码都会在你创建Handler实例的线程中运行
2. 代码示例
[java] view plain copy print?
new Thread()
{
private Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e("TAG",Thread.currentThread().getName());
};
};
Looper.loop();
}
}
new Thread()
{
private Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e("TAG",Thread.currentThread().getName());
};
};
Looper.loop();
}
}
三、应用场景三
1. 说明: 定时器
2. 示例代码
[java] view plain copy print?
private static final int LOAD_DISPLAY_TIME = 3000; // 延迟3s
new Handler().postDelayed(new Runnable() {
public void run() {
// 时间到时,执行的代码
}
}, LOAD_DISPLAY_TIME);
关闭此定时器:handler.removeCallbacks(runnable);