MisterCereal MisterCereal - 1 month ago 16
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());
handlerThread.start();
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() {
@Override
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.
useObject(o);
}
};)


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

Answer

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() {
            @Override
            public void run() {
                // do your main thread task here
            }
        });