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

后端 未结 9 883
梦如初夏
梦如初夏 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 00:52

    Stopping a thread or a process immediately is often a dirty thing. However, it should be fine if your service is stateless.

    Declare the service as a separate process in the manifest:

    And when you want to stop its execution, just kill that process:

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List runningAppProcesses = am.getRunningAppProcesses();
    
    Iterator iter = runningAppProcesses.iterator();
    
    while(iter.hasNext()){
        RunningAppProcessInfo next = iter.next();
    
        String pricessName = getPackageName() + ":service";
    
        if(next.processName.equals(pricessName)){
            Process.killProcess(next.pid);
            break;
        }
    }
    

提交回复
热议问题