Tom11
Tom11

Reputation: 2519

Stopping a Service from Activity

I have problem with stopping a service from activity.

Declaration of my service:

public class MyService extends Service implements LocationListener { .. }

This service is called when the button is pressed:

public void startMyService(View view)
{
    ComponentName comp = new ComponentName(getPackageName(), MyService.class.getName());
    ComponentName service = startService(new Intent().setComponent(comp));
}

In another method (launched by button click) I want to stop it:

public void stopMyService(View view)
{
    stopService(new Intent(this, MyService.class));
}

Unfortunately, it is not working. It seems to me that this service is replaced by another one. Furthermore, it´s cumulating - for example, when I start the service for the second time, there are two of them, running, etc. Could somebody help me? Thanks in advance for your help.

UPDATE : Android Manifest (only my service):

<service android:name=".MyService" 
        android:enabled="true" 
        android:exported="false"
        android:label="LocationTrackingService" 
        />

Upvotes: 0

Views: 1123

Answers (1)

Trinimon
Trinimon

Reputation: 13967

You could add a BroadcastReceiver to your service (or a static method - depending on your preferences) and call Context.stopService() or stopSelf(), e.g. add ...

public static String STOP_SERVICE = "com.company.SEND_STOP_SERVICE";

private final BroadcastReceiver stopReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      if(intent.getAction().equals(STOP_SERVICE)){
          MyService.this.stopSelf();
      }
   }
};

... to your service (assuming it's called MyService). Then call registerReceiver(stopReceiver, STOP_SERVICE); in the onStartCommand() method and unregisterReceiver(stopReceiver); in onDestroy(). Finally send the broadcast from anywhere you need to stop the service:

Intent intent=new Intent();
intent.setAction(MyService.STOP_SERVICE);
sendBroadcast(intent);

If you have some threads you have to stop them before (probably you have and you started the service sticky, did you?)

Upvotes: 1

Related Questions