我正在尝试使用前台服务中的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);

最佳答案

在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);

关于android - 处理程序线程: Only one Looper may be created per thread,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52083357/

10-11 15:23