其他分享
首页 > 其他分享> > android – handler.postDelayed在IntentService的onHandleIntent方法中不起作用

android – handler.postDelayed在IntentService的onHandleIntent方法中不起作用

作者:互联网

final Handler handler = new Handler();
LOG.d("delay");
handler.postDelayed(new Runnable() {
    @Override public void run() {
        LOG.d("notify!");
        //calling some methods here
    }
}, 2000);

“延迟”确实显示在日志中,但根本不显示.并且在run()中调用的方法也根本不被调用.任何人都可以帮助解释为什么会发生这种情况,我做错了吗?

具有此代码的类扩展了IntentService,这会是一个问题吗?

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

更新:
我将此代码放在扩展IntentService的类中.我发现它唯一有用的地方是构造函数.但我需要把它放在onHandleIntent方法中.所以我检查了onHandleIntent的文档,它说:

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.

所以基于我得到的结果,我觉得我不能在“工作线程”中使用postDelayed.但是,任何人都可以解释这一点,比如为什么这不适用于工作线程?提前致谢.

解决方法:

您正在使用主线程的looper.您必须创建一个新的循环器,然后将其提供给您的处理程序.

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);

或者您可以使用Thread.sleep(long millis).

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

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

如果要停止休眠线程,请使用yourThread.interrupt();

标签:intentservice,android-handler,postdelayed,android,android-intentservice
来源: https://codeday.me/bug/20190727/1555176.html