handler.postDelayed is not working in onHandleIntent method of IntentService

Zip picture Zip · Apr 30, 2016 · Viewed 9.9k times · Source
final Handler handler = new Handler();
LOG.d("delay");
handler.postDelayed(new Runnable() {
    @Override public void run() {
        LOG.d("notify!");
        //calling some methods here
    }
}, 2000);

The "delay" does shows in the log, but not others at all. And the method called in the run() is not called at all also. Can anyone help explain why this happens, am I doing anything wrong?

The class that has this code extends IntentService, will this be a problem?

============================

UPDATE: I put this code in the class that extends IntentService. The only place I found it worked was in the constructor. But I need to put it in the onHandleIntent method. So I checked the documentation for onHandleIntent and it said:

This method is invoked on the worker thread with a request to process.Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf.

So based on the result I get, I feel like I cannot use postDelayed in "worker thread". But can anyone explain this a bit more, like why this is not working in worker thread? Thanks in advance.

Answer

Kivvil picture Kivvil · Jan 22, 2018

Convert

final Handler handler = new Handler();

to

final Handler handler = new Handler(Looper.getMainLooper());

This worked for me.