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

标签 android intentservice android-handler android-intentservice postdelayed

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。但是谁能解释一下,比如为什么这在工作线程中不起作用?提前致谢。

最佳答案

转换

final Handler handler = new Handler();

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

这对我有用。

关于android - handler.postDelayed 在 IntentService 的 onHandleIntent 方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949239/

相关文章:

android - 支持库中的 WakefulBroadcastReceiver 与 commonsware 的 cwac-wakeful

java - 来自非 Activity 类的处理程序

java - getDrawingCache() 返回的位图未更新

java - Android 中的实时视频聊天流?

onCharacteristicwrite 中的 Android Ble 状态代码 14

android - 服务或 IntentService 或 AlarmManager 方法

android - 如何使用按钮终止从 IntentService 创建的 TimerTask

Android 处理程序与服务

具有网络负载和最短启动显示时间的 Android 启动画面

android - 没有 API key 的静态 map URL 仍然有效(?)