2016-12-28 133 views
2

我有两个通知操作,一个停止服务,一个重新启动它。 我成功启动该服务,但我不能使用此代码停止:Android - 通知pendingIntent停止服务

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

任何想法?

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

+5

可能重复的[PendingIntent启动和停止服务](http://stackoverflow.com/questions/20572216/pendingintent-to-launch-and-stop-a-service) –

+1

为什么你使用相同的请求两种不同行为的代码?我认为你与PendingIntent标志混淆。这些标志用于控制通知。 – Ayaanp

回答

2

仅此标志不会停止服务。我建议你制定停止行动,而不是发射一个自定义BroadcastReceiver类,该类在其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已在您的清单文件中声明e:

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

希望这有助于!