Android: How to completely kill a Service running separately as a background process?

Rob Avery IV picture Rob Avery IV · Dec 16, 2013 · Viewed 22k times · Source

I have an app that has an Activity, which is used as the regular GUI, and a Service. My activity has two buttons. One button to stop the process and one to kill the process. I use these to methods, respectively, to start and stop my process:

Intent i = null;
Button start;
Button stop;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    i = new Intent(this, Service.class);
    start = (Button) findViewbyId(R.id.start_button);
    stop = (Button) findViewById(R.id.stop_button);

    start.setOnClickListener(new OnClickListener(){

        public void onClick(){
            startService(i);
        }
    }
    stop.setOnClickListener(new OnClickListener(){

        public void onClick(){
            stopService(i);
        }
    }
}

This Service is not bound to the actvivty or app. I have the service configured in the Manifest as so:

<service
    android:name="com.example.mypackage.Service"
    android:process=":remote"> 
    <intent-filter>
        <action
            android:name="com.example.mypackage.Service" />
    </intent-filter>
</service>

When I start the Service it runs on it's own independent on anything else. Meaning, when I start the service and onDestroy() the app, the service is still running. I can see it is still running because through adb, I run the ps command and it says it is.

The problem is when I call stopService(intent). When I call stopService(intent) from the activity side, it will run the lines of code set in the onDestroy() of the service, but when I run ps through adb, it says that it's still running.

I want to be able to COMPLETELY destroy the service. I'm not sure how services work, so please, don't hesitate to talk remedial. I'm not sure if it has to do with what I'm doing within the service or not. Thanks!

EDIT: When I start the service, I use the onStartCommand() and run some code there which it does. I also return START_STICKY from onStartCommand(). I also tried returning START_NOT_STICKY and the service is still running after I call startService(intent).

Answer

Chari D picture Chari D · Jan 11, 2016

If you want kill service process forcefully, you can use following code:

Process.killProcess(Process.myPid());