gre*_*egm 11 android android-service android-notifications
我想要以下行为:用户点击通知,Android停止我的服务.
问题是停止服务需要调用stopService,我不能轻易创建一个PendingIntent来做到这一点.
因此,我发现这样做的唯一方法是让我的服务收到一个特殊的Intent额外,使服务调用stopSelf并停止.
是否有更简单的方法从通知点击中直接取消服务?
loo*_*nis 13
感谢CommonsWare.
以下是您感兴趣的人的快速解决方案.
代码在服务类中.
Run Code Online (Sandbox Code Playgroud)// 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(); } };
您可以创建一个BroadcastReceiver执行stopService()调用的简单函数,并使用a getBroadcast() PendingIntent来触发它.这BroadcastReceiver可能会在清单或通过注册registerReceiver()由Service本身(在后一种情况下,它会做的stopSelf(),而不是stopService()).
但是,这可能不比你拥有的更简单,并且没有办法直接触发stopService()来自a 的调用PendingIntent.
| 归档时间: |
|
| 查看次数: |
4347 次 |
| 最近记录: |