How to force an IntentService to stop immediately with a cancel button from an Activity?

后端 未结 9 897
梦如初夏
梦如初夏 2020-11-30 00:10

I have an IntentService that is started from an Activity and I would like to be able to stop the service immediately from the activity with a \"cancel\" button in the activi

9条回答
  •  一个人的身影
    2020-11-30 01:11

    Here is the trick, make use of a volatile static variable and check continue condition in some of lines in your service that service continue should be checked:

    class MyService extends IntentService {
        public static volatile boolean shouldContinue = true;
        public MyService() {
            super("My Service");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            doStuff();
        }
    
        private void doStuff() {
            // do something 
    
            // check the condition
            if (shouldContinue == false) {
                stopSelf();
                return;
            }
    
           // continue doing something
    
           // check the condition
           if (shouldContinue == false) {
               stopSelf();
               return;
           }
    
           // put those checks wherever you need
       }
    }
    

    and in your activity do this to stop your service,

     MyService.shouldContinue = false;
    

提交回复
热议问题