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
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:
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
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?