Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PendingIntent to launch and stop a Service

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!!!!
        }
like image 243
iGio90 Avatar asked Dec 13 '13 17:12

iGio90


People also ask

Why would you use a PendingIntent?

A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it.

What is PendingIntent Flag_update_current?

FLAG_UPDATE_CURRENT : Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.


1 Answers

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().

like image 125
Matt Avatar answered Sep 30 '22 19:09

Matt