0xiamjosh
0xiamjosh

Reputation: 573

Android Best-Way to communicate with a Foreground Service

I am bit new to android. I would like to know how to communicate with a foreground started service.

So, I got a Foreground service with a notification. This notification has a (X) button to stop the service.

The service got a Static broadcastreceiver.

public static class NotificationStopButtonHandler extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"Close Clicked",Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG, "In Closed");

            // imposible to do context.stopForground(true) or
            // to call any other private coded by me
        }
}

So my question is : Is BroadcastReceiver is the best way ? If it is : How I can communicate with the service to call stopForeground in the broadcastReceiver ?

Thanks in advance for your responses.

Same question like mien... But I would like to know which are the other solution than broadcastReceiver. thx

Upvotes: 3

Views: 2667

Answers (2)

Francesc
Francesc

Reputation: 29260

In your notification you will have a PendingIntent for the X button. I presume you have built that PendingIntent with

PendingIntent.getBroadcast(/* ... */);

What you can do instead is to create a PendingIntent for your service

Intent intent = /* intent for starting your service */;
intent.putExtra("STOP_FOREGROUND", true);
PendingIntent.getService(context, requestCode, intent, flags);

and in the intent you pass to the PendingIntent you would add an extra (STOP_FOREGROUND). When this intent is fired, your service will get called in onStartCommand(). Here you check the intent and if it contains your extra, you know you're expected to call stopForeground.

Upvotes: 1

DeeV
DeeV

Reputation: 36035

Instead of broadcasts, you can use PendingIntent with an Intent to the Service and tell the Service to shut down. You assign the PendingIntent to the close button action and/or to the notifications onDelete call when you build the notification.

Assuming that you're starting the Service with the notification, you can put commands in the Intent to tell the service to stop itself. Service#onStartCommand will be called on the service with the new Intent. The service checks for the shutdown call and calls stopSelf() when done.

Basically, the reason this works is because there can only be one Service started. Every subsequent attempt to start the service will send the intent to Service#onStartCommand, but it will not restart the Service. Thus, this is a way you can send commands to the service through means outside of binding. Plus it's way cleaner than using broadcasts.

Upvotes: 1

Related Questions