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

后端 未结 9 893
梦如初夏
梦如初夏 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:10

    I've used a BroadcastReceiver inside the service that simply puts a stop boolean to true. Example:

    private boolean stop=false;
    
    public class StopReceiver extends BroadcastReceiver {
    
       public static final String ACTION_STOP = "stop";
    
       @Override
       public void onReceive(Context context, Intent intent) {
           stop = true;
       }
    }
    
    
    @Override
    protected void onHandleIntent(Intent intent) {
        IntentFilter filter = new IntentFilter(StopReceiver.ACTION_STOP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        StopReceiver receiver = new StopReceiver();
        registerReceiver(receiver, filter);
    
        // Do stuff ....
    
        //In the work you are doing
        if(stop==true){
            unregisterReceiver(receiver);
            stopSelf();
        }
    }
    

    Then, from the activity call:

    //STOP SERVICE
    Intent sIntent = new Intent();
    sIntent.setAction(StopReceiver.ACTION_STOP);
    sendBroadcast(sIntent);
    

    To stop the service.

    PD: I use a boolean because In my case I stop the service while in a loop but you can probably call unregisterReceiver and stopSelf in onReceive.

    PD2: Don't forget to call unregisterReceiver if the service finishes it's work normally or you'll get a leaked IntentReceiver error.

提交回复
热议问题