我正在尝试使用前台服务中的Handler
和HandlerThread
在新线程上执行任务。但是当我打电话给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);
答案 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);