14

I'm trying to make a simple widget with a button that start a Service with the OnClickPendingIntent(). I can start it fine but I can't figure out a way to stop it (I know I can do it with a BroadcastReceiver or something similar but I would like to avoid hardcode).

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!!!!
        }
Sufian
  • 6,405
  • 16
  • 66
  • 120
iGio90
  • 3,251
  • 7
  • 30
  • 43

2 Answers2

29

There are multiple ways to do this, here's 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 on the service's onStartCommand(), you can check the intent action for "STOP" (you should probably use a better string) and call stopSelf().

Sufian
  • 6,405
  • 16
  • 66
  • 120
Matt
  • 3,837
  • 26
  • 29
-1

I created Xamarin android signal program, but when the signal comes, I can't show the signal, that is, the program does not open automatically

  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/33646956) – JustSightseeing Jan 22 '23 at 02:59