PendingIntent to start and stop the service

I am trying to create a simple widget with a button that launches a Service using OnClickPendingIntent() . I can start everything normally, but I can’t figure out how to stop it (I know I can do it using BroadcastReceiver or something like that, but I would like to avoid hard code).

This is my code:

  Intent intent = new Intent(context, myService.class); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget); if (!ismyserviceup(context)) { views.setOnClickPendingIntent(R.id.my_button, pendingIntent); } else { // i need to stop it!!!! } 
+6
source share
1 answer

There are several ways to do this, here is one:

  Intent intent = new Intent(context, myService.class); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget); if (ismyserviceup(context)) { intent.setAction("STOP"); } PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.my_button, pendingIntent); 

Then in the onStartCommand() you can check the intent action for "STOP" (maybe you should use the best line) and call stopSelf() .

+17
source

All Articles