开发者

Why does Android service needs to run on UI thread?

I have a probably simple question. I have an android service; where in I have created a generic service class which requests locks and executes actual (extending) service code in a separate thread. Example below:

abstract public class ParentService extends Service {


public static void getLocks(Context context) {
       //code to get locks
}

public abstract void doServiceJob();

@Override
public void onCreate() {
    super.onCreate();       
    //Run the service code in separate thread
    Thread serviceThread = new Thread() {
        public void run() {
            //Looper.prepare();
            doServiceJob();
            //Looper.loop();
        }
    };
    serviceThread.start();
}

@Override
public void onDestroy() {
       //release locks
}
}

In above example; everything works fine even if Looper.prepare() and Looper.loop() are not called in invoked thread.

However if I try to get location through GPS or Network; then I have a problem, and code doesn't run saying that "Can't create handler inside thread that has not called Looper.prepare()".

I understand that we need to create looper and handler to communicate to UI thread; for events that affect UI. However does fetching location affects UI? Is it because the location provider will also try to draw a GPS icon on my phone top bar and since it's not running in UI thread; it cannot do that?

What is the issue here, I can fix this issue by calling looper.prepare() and Looper.loop(); however I need to understand following things?

  • I know service runs on main thread, which is same as UI thread; does that effectively means, service has ability to make changes to UI and we do not do it because it's not good user experience and thats why communicate everything through notifications? (Even notifications need to开发者_StackOverflow社区 run on UI thread?)
  • Why does location provider needs to run on UI thread?
  • I am not declaring any handler here, I am just calling a looper.prepare(); so how does the message queuing works in background and what happens down below in android code?

Any pointers and answers to these questions will be really helpful. Thanks in advance for your help.

Cheers


The reason why you have to call Looper.Loop is that it provides the route through which background operations execute code on the foreground thread. Messages from background threads are posted onto the UI thread using Handler objects, and these, in turn require the UI thread to call Looper.Loop to get the actual messages serviced. That's where message procesing takes place: within the Looper.Loop call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜