handler.postDelayed is not working in onHandleIntent method of IntentService

隐身守侯 提交于 2019-12-01 17:52:21

You are using looper of the main thread. You must create a new looper and then give it to your handler.

HandlerThread handlerThread = new HandlerThread("background-thread");
handlerThread.start();
final Handler handler = new Handler(handlerThread.getLooper());
handler.postDelayed(new Runnable() {
    @Override public void run() {
        LOG.d("notify!");
        // call some methods here

        // make sure to finish the thread to avoid leaking memory
        handlerThread.quitSafely();
    }
}, 2000);

Or you can use Thread.sleep(long millis).

try {
    Thread.sleep(2000);
    // call some methods here

} catch (InterruptedException e) {
    e.printStackTrace();
}

If you want to stop a sleeping thread, use yourThread.interrupt();

Convert

final Handler handler = new Handler();

to

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

This worked for me.

Handlers and Services will be predictable when the device screen is on. If the devices goes to sleep for example the Handler will not be a viable solution.

A much more better and reliable solution will be to use: AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

BriniH

IntentService is not designed for such scenario. You can use a regular Service instead. You can put the handler inside the onStartCommand(). Don't forget to call stopSelf() on the Service instance to shut it down after the handler.postDelayed(){}

this is how i use handler:

import android.os.Handler;

Handler handler;
//initialize handler
handler = new Handler();

//to start handler
handler.post(runnableName);

private Runnable runnableName= new Runnable() {
        @Override
        public void run() {
            //call function, do something
            handler.postDelayed(runnableName, delay);//this is the line that makes a runnable repeat itself
        }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!