问题描述
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()
中调用的方法也根本不会被调用.任何人都可以帮助解释为什么会发生这种情况,我做错了什么吗?
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?
具有此代码的类扩展了IntentService,这会成为问题吗?
The class that has this code extends IntentService, will this be a problem?
===========================
============================
更新:我将此代码放在扩展IntentService
的类中.我发现它起作用的唯一地方是在构造函数中.但是我需要将其放在onHandleIntent
方法中.因此,我查看了onHandleIntent
的文档,并说:
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:
因此,根据得到的结果,我觉得我无法在工作线程"中使用postDelayed
.但是,谁能解释得更多,例如为什么这在工作线程中不起作用?预先感谢.
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.
推荐答案
您正在使用主线程的循环程序.您必须创建一个新的循环程序,然后将其提供给您的处理程序.
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);
或者您可以使用Thread.sleep(长毫秒).
Or you can use Thread.sleep(long millis).
try {
Thread.sleep(2000);
// call some methods here
} catch (InterruptedException e) {
e.printStackTrace();
}
如果要停止休眠线程,请使用yourThread.interrupt();
If you want to stop a sleeping thread, use yourThread.interrupt();
这篇关于handler.postDelayed在IntentService的onHandleIntent方法中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!