简体   繁体   English

Android - 通知pendingIntent停止服务

[英]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). 不是重复,因为我的问题是关于通知操作,而不是按钮(我没有问题让我的按钮停止并启动服务)。

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() . 我建议您进行停止操作,而不是触发一个自定义的BroadcastReceiver类,该类在其onReceive()内部运行stopService()方法。 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: 将隐藏操作的IntentPendingIntent更改为:

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: 然后像这样制作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);
    }
}

Make sure the BroadcastReceiver you just made is declared in your manifest file: 确保您在清单文件中声明刚刚创建的BroadcastReceiver

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

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM