Does a runnable in a service run on the UI thread

风格不统一 提交于 2019-11-29 10:20:10

问题


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);

回答1:


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());



回答2:


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




回答3:


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




回答4:


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?



来源:https://stackoverflow.com/questions/14808640/does-a-runnable-in-a-service-run-on-the-ui-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!