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);
The runnable you submit to your handler will be always executed on the UI thread, since service are not spawn on a different process or threda, but thy are part of hte UI thread
By default services runs in UI thread. But it depends on service type and service properties and the way you post runnable. I think that you use default scheme and your runnable will be executed on UI thread and block it.
If you show code how you post runnable and create service I can give you exact answer.
You can check thread type from your runnable using following code:
It is still not clear. If you execute "new Handler()" on UI thread than runnable will be executed on UI thread. If you execute "new Handler()" on another thread with looper than runnable will be executed on that thread. I think with probability 99% your runnable will be executed on UI thread. Why don't you place my code in runnable and check where it is executed?
Docs:
Different thread:
UI/Service Thread:
No it is not part of
UI thread
, I assume byRunnable
you mean a new thread that you execute by callingstart()
.Regardless if you start a new
Thread
in aservice
oractivity
it will not be part of the UI thread (unless you call something likejoin()
)Edit
Since you are running a
Runnable
object withHandler
, so it depends on where you initialize yourhandler
. Service runs in themain thread
, so initializing the handler in a service or activity will make the code be posted to theUI 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 insteadhandler.postDelayed(runnable, 1000);
wherehandler
is an instance variable initialized in your service/activity class