Can't create handler inside thread Thread[Thread-3,5,main] that has not called Looper.prepare() 原因
时间: 2023-09-06 18:07:05 浏览: 165
这个错误通常发生在 Android 应用程序中,它表示您正在尝试在没有调用 `Looper.prepare()` 的线程中创建一个处理程序。Looper 是 Android 中的一种机制,用于管理线程的消息循环。如果您想在一个新的线程中创建一个处理程序,您应该首先调用 `Looper.prepare()` 方法,然后在调用 `Looper.loop()` 方法之前将处理程序附加到该线程的消息队列中。
以下是一个示例代码,演示了如何在 Android 应用程序中使用 Looper 和 Handler:
```
class MyThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// 处理消息
}
};
Looper.loop();
}
}
```
在上面的代码中,我们创建了一个自定义线程 `MyThread`,并在其 `run()` 方法中调用了 `Looper.prepare()` 和 `Looper.loop()` 方法。我们还为线程创建了一个处理程序 `mHandler`,该处理程序可以处理在该线程中发送的消息。现在,我们可以在其他线程中使用 `mHandler` 对象来向该线程发送消息,例如:
```
MyThread thread = new MyThread();
thread.start();
thread.mHandler.sendMessage(Message.obtain());
```
请注意,在发送消息之前,我们必须等待 `MyThread` 线程启动并创建处理程序 `mHandler`。这可以通过一些机制(例如等待 `MyThread` 线程发出信号)来实现。
阅读全文