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

Zip*_*Zip 7 android postdelayed intentservice android-handler android-intentservice

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 Code Online (Sandbox Code Playgroud)

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

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

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

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

在工作线程上调用此方法并处理请求.一次只处理一个Intent,但处理发生在独立于其他应用程序逻辑运行的工作线程上.因此,如果此代码需要很长时间,它将阻止对同一个IntentService的其他请求,但它不会阻止其他任何内容.处理完所有请求后,IntentService会自行停止,因此您不应该调用stopSelf.

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

Ash*_*win 9

您正在使用主线程的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);
Run Code Online (Sandbox Code Playgroud)

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

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

} catch (InterruptedException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

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


小智 7

兑换

final Handler handler = new Handler();
Run Code Online (Sandbox Code Playgroud)

final Handler handler = new Handler(Looper.getMainLooper());
Run Code Online (Sandbox Code Playgroud)

这对我有用。


rma*_*alo 1

这就是我使用处理程序的方式:

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
        }
};
Run Code Online (Sandbox Code Playgroud)