Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Notification pendingIntent to Stop Service

I have two notification actions, one to stop the service and one to restart it. I am successfully starting the service but I can't stop it with this code:

PendingIntent show = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent hide = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_CANCEL_CURRENT);

Any ideas?

Not a duplicate as my question is specifically about notification actions, not buttons (I have no problems getting my buttons to stop and start the service).

like image 871
Code Poet Avatar asked Dec 28 '16 09:12

Code Poet


People also ask

What is a PendingIntent Android?

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.

How do I start a pending intent Service?

Intent intent = new Intent(context, myService. class); PendingIntent pendingIntent = PendingIntent. getService(context, 0, intent, 0); RemoteViews views = new RemoteViews(context. getPackageName(), R.

How do I turn off foreground notification?

On a phone running Android 13, it's easy to find and use the Foreground Services Task Manager: RECOMMENDED VIDEOS FOR YOU... 1. Swipe down from the top of your screen to pull down the notification shade.


1 Answers

That flag alone will not stop the service. I would recommend that you make the stop action instead fire a custom BroadcastReceiver class which runs the stopService() method inside of its onReceive(). Let me know if you need help setting something like that up in more detail.

Edited answer:

Change your Intent and PendingIntent for the hide action to this:

Intent intentHide = new Intent(this, StopServiceReceiver.class);

PendingIntent hide = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), intentHide, PendingIntent.FLAG_CANCEL_CURRENT);

Then make the StopServiceReceiver like this, where ServiceYouWantStopped.class is the service to be stopped:

public class StopServiceReceiver extends BroadcastReceiver {
    public static final int REQUEST_CODE = 333;

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, ServiceYouWantStopped.class);
        context.stopService(service);
    }
}

Make sure the BroadcastReceiver you just made is declared in your manifest file:

<receiver
    android:name=".StopServiceReceiver"
    android:enabled="true"
    android:process=":remote" />

Hope this helps!

like image 105
Nick Friskel Avatar answered Sep 27 '22 17:09

Nick Friskel