Search code examples
androidserviceforeground

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


Solution

  • 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.