Xamarin.Forms集成Azure推送通知:Android端应用前台时点击通知无法自动关闭的问题求助
解决Xamarin.Forms Android前台点击推送通知不自动关闭的问题
你遇到的这个问题是Android平台的常见行为:当应用处于前台活跃状态时,系统不会自动清除已点击的推送通知,而后台状态下系统会帮我们自动处理。要搞定这个问题,我们只需要在点击通知后手动调用NotificationManager取消对应的通知就行。
第一步:修改通知Intent,带上通知ID
在你的ShowNotification方法里,把生成的通知ID(也就是_messageId)添加到Intent的Extra参数中,这样点击通知打开MainActivity时,就能拿到这个ID用于取消通知:
public int ShowNotification(string message, string title, string pageName, string appName,string NotificationMessage) { if (!channelInitialized) { CreateNotificationChannel(); } _messageId++; Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); intent.PutExtra("title", title); intent.PutExtra("message", message); intent.PutExtra("OpenPage", pageName); intent.PutExtra("AppName", appName); intent.PutExtra("NotificationMessage", NotificationMessage); // 新增:把通知ID传递到Intent里 intent.PutExtra("NotificationId", _messageId); var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot); NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, ChannelId) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetContentText(message) .SetSmallIcon(Resource.Drawable.addovation_icon) .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate); Notification notification = builder.Build(); _manager.Notify(_messageId, notification); return _messageId; }
第二步:在MainActivity的OnNewIntent中取消通知
修改OnNewIntent方法,取出Intent里的通知ID,然后调用NotificationManager来取消这条通知:
protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); ProcessNotificationActions(intent); CreateNotificationFromIntent(intent); // 新增:获取通知ID并手动取消通知 if (intent.HasExtra("NotificationId")) { int notificationId = intent.GetIntExtra("NotificationId", -1); if (notificationId != -1) { var notificationManager = (NotificationManager)GetSystemService(NotificationService); notificationManager.Cancel(notificationId); } } LoadApplication(new App(PushNotificationFirebaseMessagingService.PushNotificationPageName, PushNotificationFirebaseMessagingService.PushNotificationAppName, PushNotificationFirebaseMessagingService.Notification)); }
补充说明
- 为什么后台状态下正常?因为当应用在后台时,点击通知后Android系统会自动帮我们清除这条通知;但前台时系统认为应用已经处于活跃状态,不会自动处理,所以必须我们手动取消。
- 如果你不想在MainActivity里重新获取NotificationManager,也可以直接使用你在通知服务里的全局
_manager实例,效果是一样的。
这样修改之后,不管应用是在前台还是后台,点击推送通知后通知都会正常关闭了。
内容的提问来源于stack exchange,提问作者AlexDemo
相关产品推荐
相关产品推荐

