In Android, when I create a runnable inside a service and run it, while I realize it runs in its own thread, is this thread somehow part of the UI thread? In other words, if the runnable carried out a long process, would it affect the UI?
EDIT:
private class SomeRunnable implements Runnable
{
@Override
public void run()
{
try
{
}
}
}
SomeRunnable runnable = new SomeRunnable();
(new Handler()).postDelayed(runnable, 1000);
Docs:
A services runs in the same process as the application in which it is declared and in the main thread of that application,
Different thread:
Thread t = new Thread(new MyRunnable());
t.start();
UI/Service Thread:
Handler h = new Handler();
h.post(new MyRunnable());
No it is not part of UI thread
, I assume by Runnable
you mean a new thread that you execute by calling start()
.
Regardless if you start a new Thread
in a service
or activity
it will not be part of the UI thread (unless you call something like join()
)
Edit
Since you are running a Runnable
object with Handler
, so it depends on where you initialize your handler
. Service runs in the main thread
, so initializing the handler in a service or activity will make the code be posted to the UI thread
Note, you need a single Handler
object per your thread; so avoid creating a new one with every time e.g. (new Handler()).postDelayed(runnable, 1000);
should be avoided and instead handler.postDelayed(runnable, 1000);
where handler
is an instance variable initialized in your service/activity class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With