MisterCereal MisterCereal - 11 months ago 60
Android Question

How can I jump from a Handler started from a service to the service's thread?

I use a Handler in my Service class to do some background work, but when it's done, I must execute some code on the Service's thread. Here's my code:

I create a handler in the Service's onCreate method.

HandlerThread handlerThread = new HandlerThread(getPackageName());
Looper looper = handlerThread.getLooper();
mHandler = new Handler(looper);

How I use the Handler. This method is getting called dozens of times during a session.

mHandler.post(new Runnable() {
public void run() {
// It takes a few seconds to execute this method,
// so it must be running on a separate thread.
Object o = superMethod();

// However, this MUST be called from the Service's thread.

So how can I get back to the Service's thread?

Answer Source

Service itself runs on main thread here you want switch from Handler Thread(Background thread) to service(main Thread).

Handler handler = new Handler(getMainLooper());
        handler .post(new Runnable() {
            public void run() {
                // do your main thread task here