Android - 通知pendingIntent停止服务

Cod*_*oet 6 java android android-notifications android-pendingintent

我有两个通知操作,一个用于停止服务,另一个用于重新启动服务.我正在成功启动该服务,但我无法使用此代码阻止它:

PendingIntent show = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent hide = PendingIntent.getService(this, 1, svc, PendingIntent.FLAG_CANCEL_CURRENT);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

不是重复,因为我的问题是关于通知操作,而不是按钮(我没有问题让我的按钮停止并启动服务).

Nic*_*kel 6

仅该标志不会停止服务。我建议您让stop动作触发一个自定义BroadcastReceiver类,该类在其中运行该stopService()方法onReceive()。让我知道您是否需要帮助来详细设置类似内容。

编辑答案:

更改IntentPendingIntent用于隐藏行动,这一点:

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

PendingIntent hide = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), intentHide, PendingIntent.FLAG_CANCEL_CURRENT);
Run Code Online (Sandbox Code Playgroud)

然后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);
    }
}
Run Code Online (Sandbox Code Playgroud)

确保BroadcastReceiver清单文件中声明了刚创建的文件:

<receiver
    android:name=".StopServiceReceiver"
    android:enabled="true"
    android:process=":remote" />
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 不再适用于Android 26,它将仅打印`BroadcastQueue:不允许后台执行` (2认同)