【问题标题】:When should we use Looper in Android?我们什么时候应该在 Android 中使用 Looper?
【发布时间】:2012-06-09 07:18:47
【问题描述】:
谁能告诉我什么时候应该在处理程序中使用 Looper?我有一个代码库,其中有多个线程和处理程序。但是Looper.prepare() 和Looper.loop() 并不是所有人都需要的。
我的疑问是我们是否需要 looper 来持续处理 handleMessage 方法中的消息?即使我们没有looper,当消息发送到处理程序时,不会调用handleMessage()吗? Looper 在这里还有什么额外的用途?
谢谢,
害羞
【问题讨论】:
标签:
android
handlers
looper
【解决方案1】:
用于为线程运行消息循环的类。默认情况下,线程没有与之关联的消息循环;创建一个,在要运行循环的线程中调用 prepare(),然后 loop() 让它处理消息,直到循环停止。
与消息循环的大多数交互是通过 Handler 类进行的。
下面是线程的run方法
@Override
public void run() {
try {
// preparing a looper on current thread
// the current thread is being detected implicitly
Looper.prepare();
Log.i(TAG, "DownloadThread entering the loop");
// now, the handler will automatically bind to the
// Looper that is attached to the current thread
// You don't need to specify the Looper explicitly
handler = new Handler();
// After the following line the thread will start
// running the message loop and will not normally
// exit the loop unless a problem happens or you
// quit() the looper (see below)
Looper.loop();
Log.i(TAG, "DownloadThread exiting gracefully");
} catch (Throwable t) {
Log.e(TAG, "DownloadThread halted due to an error", t);
}
}