Android - 停止服务的未决意图通知

Android - Notification pendingIntent to Stop Service

我有两种通知操作,一种是停止服务,另一种是重新启动服务。 我已成功启动该服务,但我无法使用此代码停止它:

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

有什么想法吗?

不是重复问题,因为我的问题专门针对通知操作,而不是按钮(让我的按钮停止和启动服务没有问题)。

仅此标志不会停止服务。我建议您执行停止操作,而不是触发自定义 BroadcastReceiver class,它在其 onReceive() 中运行 stopService() 方法。如果您需要帮助来更详细地设置类似内容,请告诉我。

编辑后的答案:

将隐藏操作的 IntentPendingIntent 更改为:

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" />

希望对您有所帮助!