Android的Looper如何使用
在Android中,Looper是用来将一个线程与一个消息队列关联起来的类。它可使线程能够处理来自消息队列的消息。
下面是一些使用Looper的步骤:
Looper.getMainLooper()
方法来获得主线程的Looper对象。在其他线程中,可使用Looper.myLooper()
方法来获得当前线程的Looper对象。Looper.prepare()
方法来为该线程创建Looper对象。Looper.loop()
方法来启动消息循环,将该线程的Looper对象与消息队列关联起来。sendMessage()
方法来发送消息,通太重写Handler的handleMessage()
方法来处理消息。下面是一个使用Looper的例子:
// 在其他线程中使用Looper
// 在其他线程中创建Handler对象
Handler handler = new Handler();
// 在其他线程中调用Looper.prepare()方法创建Looper对象
Looper.prepare();
// 在其他线程中调用Looper.loop()方法启动消息循环
Looper.loop();
// 在其他线程中使用Handler对象发送和处理消息
handler.post(new Runnable() {
@Override
public void run() {
// 发送消息
handler.sendMessage(handler.obtainMessage(1, "Hello"));
// 处理消息
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理消息逻辑
}
};
}
});
注意,使用Looper时需要注意消息的处理不要阻塞主线程,以避免致使ANR(Application Not Responding)毛病。
TOP