Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a runnable in a service run on the UI thread

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);
like image 276
Johann Avatar asked Dec 12 '22 17:12

Johann


2 Answers

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());
like image 149
S.D. Avatar answered Dec 14 '22 07:12

S.D.


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

like image 38
iTech Avatar answered Dec 14 '22 07:12

iTech