Whether running on a service on the UI thread
In Android, when I create a runnable inside a service and start it, while I realize that it is running on its own thread, is that thread somehow part of the UI thread? In other words, if the runnable was running a lengthy 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);
source to share
Docs:
Services are executed in the same process as the application in which it is declared and in the main thread of this application,
Different stream:
Thread t = new Thread(new MyRunnable());
t.start();
User / Service Stream:
Handler h = new Handler();
h.post(new MyRunnable());
source to share
No, it is not part of it UI thread
, I am assuming Runnable
you mean the new thread that you are executing by calling start()
.
No matter if you start a new one Thread
in service
or activity
, it will not be part of the UI thread (unless you call something like join()
)
Edit
Since you are using an object Runnable
with Handler
, so it will depend on where you * initialize8 yours Handler
. The service starts at main thread
, so initializing a handler on the service or activity will cause the code to be sent toUI thread
Note, you only need one Handler
object in your thread; so avoid creating a new one every time eg. (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
source to share
By default, services run on the UI thread. But it depends on the type of service and the properties of the service, as well as how you dispatch the runnable. I think you are using the default schema and your runnable will execute on the UI thread and block it.
If you show the code how you dispatch the runnable and create the service, I can give you the exact answer.
You can check the thread type from your runnable using the following code:
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
It's not clear yet. If you execute "new handler ()" on the UI thread, than the runnable will run on the UI thread. If you execute "new handler ()" on another thread using a looper, then the runnable will be executed on that thread. I think there is a 99% chance your runnable will be executed on the UI thread. Why don't you put my code in a runnable and check where it runs?
source to share