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

gre*_*egm 11 android android-service android-notifications

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

问题是停止服务需要调用stopService,我不能轻易创建一个PendingIntent来做到这一点.

因此,我发现这样做的唯一方法是让我的服务收到一个特殊的Intent额外,使服务调用stopSelf并停止.

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

loo*_*nis 13

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

  • 接收器是否需要"未注册"? (4认同)

Com*_*are 6

您可以创建一个BroadcastReceiver执行stopService()调用的简单函数,并使用a getBroadcast() PendingIntent来触发它.这BroadcastReceiver可能会在清单或通过注册registerReceiver()Service本身(在后一种情况下,它会做的stopSelf(),而不是stopService()).

但是,这可能不比你拥有的更简单,并且没有办法直接触发stopService()来自a 的调用PendingIntent.

  • @gnobal:`DeadObjectException`只能通过绑定AFAIK来实现.该解决方案不涉及绑定. (2认同)