Reputation: 663
I am trying to use Handler
and HandlerThread
from foreground service to execute task on new thread. But when I call HandlerThread.run()
I get java.lang.RuntimeException: Only one Looper may be created per thread
I am starting the thread using this code:
networkThread = new HandlerThread("Network Thread");
if(networkThread.getLooper() == null)
networkThread.run();
handler = new Handler(networkThread.getLooper());
handler.postDelayed(updateTask, 1000);
Upvotes: 2
Views: 1321
Reputation: 14173
In android each Thread
has only one Looper
, when you use HandlerThread
, it creates a Looper
when you start the handler thread.
HandlerThread
is just a java Thread
which has a Looper
.
Root cause: Your code is not correct.
Solution: Change your code
From
networkThread = new HandlerThread("Network Thread");
if(networkThread.getLooper() == null)
networkThread.run();
handler = new Handler(networkThread.getLooper());
handler.postDelayed(updateTask, 1000);
To
// 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);
Upvotes: 2