android - 是否有一种直接的方法来响应用户单击通知来停止服务?

标签 android android-service android-notifications

我想要以下行为: 用户点击通知,Android 停止我的服务。

问题是停止服务需要调用 stopService,而我无法轻松地创建执行此操作的 PendingIntent。

所以我发现这样做的唯一方法是让我的服务接收一个特殊的 Intent extra,它会导致服务调用 stopSelf 并停止。

是否有更简单的方法直接通过通知点击取消服务?

最佳答案

感谢 CommonsWare。

这里是您的解决方案的简要说明,供有兴趣的人使用。

代码在服务类中。

// Create Notification 
private void initNotification() {     
  //Register a receiver to stop Service   
  registerReceiver(stopServiceReceiver, new IntentFilter("myFilter"));
  PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, new Intent("myFilter"), PendingIntent.FLAG_UPDATE_CURRENT);
  notification.setLatestEventInfo(context, contentTitle, contentText,contentIntent);  
  mNotificationManager.notify(NOTIFICATION_ID,notification);  
...
}



//We need to declare the receiver with onReceive function as below
protected BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {   
  @Override
  public void onReceive(Context context, Intent intent) {
  stopSelf();
  }
};

关于android - 是否有一种直接的方法来响应用户单击通知来停止服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241682/

相关文章:

android - 如何处理一个巨大的 JSON 数组?

java - IntentService/Service - 即使应用程序终止也保持运行 - Android

android - 解析.com : Sending a localized push notification to Android client - what does the client implementation look like?

android - 从服务通知恢复应用程序

android - Android Nougat 升级中的 Recyclerview 问题

android - 在移动到另一个 Activity 时保存 Android 中的 Activity

Activity 崩溃后android停止后台服务

如果我使用 intent 进入主屏幕,Android 服务将被终止

java - Android 通知打开当前正在运行的应用程序而不是创建新进程?

android - 在 Android 中调用 .NET Web API Post Service 发送空消息