make an IntentService not sleep until it executes a handler.postDelayed runnable

懵懂的女人 提交于 2019-12-02 06:23:12

问题


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);
        //...
   }
   //...
}

回答1:


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.




回答2:


You need to stop onHandleIntent from returning until the Runnable has completed. This can be achieved by using a CountdownLatch, which awaits at the end of your onHandleIntent method, and gets released at the end of the run method.

NOTE: this will cause the intent service to not process other Intents you sent it until the previous one has completed (after 20 seconds).

You may also want to obtain a partial wakelock at the start of onHandleIntent and release it at the end.



来源:https://stackoverflow.com/questions/21407161/make-an-intentservice-not-sleep-until-it-executes-a-handler-postdelayed-runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!