Search code examples
androidservicebackground-process

How do you properly terminate a Service, stopService() not working?


Unable to terminate a Service created in Android, it remains running after stopService. Starting the services as follows:

    Intent i = new Intent(this, MyService.class);
    startService(i);

Associated Manifest entry:

 <service android:name=".services.MyService" ></service>

The gist of MyService that will persist across several activities, so I did not use a IntentService:

package com.sample.app.services;

public class MyService extends Service {

public static final String TAG = MyService.class.getSimpleName();
private Handler handler;

protected void onHandleIntent(Intent intent) {


    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getBaseContext(), "MyService Intent...  Start", Toast.LENGTH_LONG).show();
        }
    });

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    handler = new Handler();

            myProcessing();

    //  This will cause the service to hang around
    return (START_STICKY);
}


@Override
public IBinder onBind(Intent intent) {
    return (null);
}

@Override
public void onDestroy() {
    super.onDestroy();

    }
}

In various activities and even attempted it in onDestroy() above, prior to super.onDestroy(); above I tried the following:

        Intent i = new Intent(this, MyService.class);
    stopService(i);

MyService just continues to run. I believe by definition the service is a Singleton.


Solution

  • If you want to stop the serivce there are two ways you can do it,

    1) Call stopself() within in the service class.

    2) Using stopService().

    IN your case , Saying that your service class is in a diferrent package (even if it's in the same package thats fine) it's better you use aa intent filter for your service, which makes it easy to stop and start a service like the below.

    <service android:name=".services.MyService" android:enabled="true">
            <intent-filter android:label="@string/myService" >
                <action   android:name="custom.MY_SERVICE"/>
            </intent-filter>
        </service>
    

    and add this in your service class

    public static final String ServiceIntent = "custom.MY_SERVICE"
    

    and then you can start or stop the service like the below.

    startService(new Intent(MyService.ServiceIntent));
    stopService(new Intent((MyService.ServiceIntent));
    

    Hope this is helpfull. Thankyou