2

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);
        //...
   }
   //...
}
ahmed_khan_89
  • 2,755
  • 26
  • 49

2 Answers2

4

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • This is the same issue, is that correct? https://stackoverflow.com/questions/36949239/handler-postdelayed-is-not-working-in-onhandleintent-method-of-intentservice Why exactly, would you know? Basically, my app is still in foreground and screen is still on, and still this doesn't work... creating a new HandlerThread for network tasks when IntentService is available sounds like overkill unless a solid reason be there. Pls... – AA_PV May 25 '17 at 21:55
  • @AA_PV: `HandlerThread` is *much* lighter-weight than is `IntentService`. – CommonsWare May 25 '17 at 22:32
1

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.

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37