处理程序线程:每个线程只能创建一个Looper

时间:2018-08-29 17:42:52

标签: android multithreading

我正在尝试使用前台服务中的HandlerHandlerThread在新线程上执行任务。但是当我打电话给HandlerThread.run()时,我得到java.lang.RuntimeException: Only one Looper may be created per thread

我正在使用以下代码启动线程:

networkThread = new HandlerThread("Network Thread");
    if(networkThread.getLooper() == null)
        networkThread.run();

handler = new Handler(networkThread.getLooper());
handler.postDelayed(updateTask, 1000);

1 个答案:

答案 0 :(得分:1)

在android中,每个Thread只有一个Looper,当您使用HandlerThread时,它会在启动处理程序线程时创建一个Looper

HandlerThread只是具有Thread的Java Looper

根本原因:您的代码不正确。

解决方案:更改代码

来自

networkThread = new HandlerThread("Network Thread");
    if(networkThread.getLooper() == null)
        networkThread.run();

handler = new Handler(networkThread.getLooper());
handler.postDelayed(updateTask, 1000);

收件人

// Create and start a handler thread.
networkThread = new HandlerThread("Network Thread");
networkThread.start(); 

handler = new Handler(networkThread.getLooper()); // The calling thread must wait until a Looper has been created in the handler thread.

// Post your task to handler thread to process
handler.postDelayed(updateTask, 1000);