使不睡的IntentService直到它执行handler.postDelayed可运行 [英] make an IntentService not sleep until it executes a handler.postDelayed runnable

查看:342
本文介绍了使不睡的IntentService直到它执行handler.postDelayed可运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的我IntentService类onHandleIntent,我创建了处理包含一个可运行应在20秒后完成。不幸的是我睡的服务或此期间之前被破坏。
我也试图与CountDownTimer,但我有同样的问题。
难道有人有任何想法,我可以让onHnadleIntent等待?谢谢!

这是code:

 公共类的MyService扩展IntentService {
    // ...
    @覆盖
    保护无效onHandleIntent(意向workIntent){
        处理程序处理程序=新的处理程序();
        handler.postDelayed(新的Runnable(){
        @覆盖
        公共无效的run(){
            Log.i(进行20秒以后,我在这里);
            }
        },20000);
        // ...
   }
   // ...
}


解决方案

不要使用 IntentService 。它是不适合您的方案。使用普通的服务。把你的code在 onStartCommand()。在你的的run()方法,调用 stopSelf()服务的底部实例将其关闭。

In the onHandleIntent of my my IntentService class, I created handle containing a runnable which should be done after 20 seconds. Unfortunatly my service sleeps or is destroyed before this period. I tried also with the CountDownTimer, but i had the same problem. Do someone have any idea can I make the onHnadleIntent waiting? Thank you!

This is the code:

 public class MyService extends IntentService {
    //...
    @Override
    protected void onHandleIntent(Intent workIntent) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.i("20 seconds later","I am here");
            }
        }, 20000);
        //...
   }
   //...
}

解决方案

Don't use an IntentService. It is not designed for your scenario. Use a regular Service. Put your code in onStartCommand(). At the bottom of your run() method, call stopSelf() on the Service instance to shut it down.

这篇关于使不睡的IntentService直到它执行handler.postDelayed可运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆