安卓 - 通知pendingIntent停止服务

6

我有两个通知动作,一个是停止服务,另一个是重启服务。我可以成功启动服务,但无法使用以下代码停止它:

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

你有什么想法吗?

这不是一个重复的问题,因为我的问题特别涉及到通知操作,而不是按钮(我没有任何问题让我的按钮停止和启动服务)。


5
可能是 PendingIntent to launch and stop a Service 的重复问题。 - Charuක
1
你为什么在两个不同的操作中使用相同的请求代码?我觉得你对PendingIntent标志感到困惑。这些标志用于控制通知。 - Ayaanp
1个回答

6
那个标志本身不会停止服务。我建议您将停止操作改为触发自定义BroadcastReceiver类,该类在其onReceive()内运行stopService()方法。如果需要更详细的设置帮助,请告诉我。 编辑后的答案: 将隐藏操作的Intent和PendingIntent更改为以下内容:
Intent intentHide = new Intent(this, StopServiceReceiver.class);

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

然后,将StopServiceReceiver制作成这样,其中ServiceYouWantStopped.class是要停止的服务:
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);
    }
}

请确保您刚刚创建的BroadcastReceiver在清单文件中声明:

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

希望这能帮到你!

3
不再适用于 Android 26,它将简单地打印“BroadcastQueue: Background execution not allowed”。 - Martin Vysny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接