我有一个Xamarin.Forms应用程序,它有一个派生自GcmServiceBase的类,用于检索Android中的notifcations。Xamarin复制订阅点击通知时
这一类onMessage方法包括以下代码:
string messageText = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(messageText))
{
MessagingCenter.Send<INotifier, AlertModel>
(this, "myalert", new AlertModel(messageText));
CreateNotification("this is a notification...", messageText, context);
}
private void CreateNotification(string title, string desc, Context context)
{
var intent = new Intent(context, typeof(MainActivity));
const int pendingIntentId = 0;
var pendingIntent = PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent);
Notification.Builder builder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(desc)
.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
.SetSmallIcon(Resource.Drawable.Icon);
var notification = builder.Build();
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
但是这是造成问题。当我从状态栏中单击通知时,它将再次创建页面,因此订阅警报的订阅者不止一次订阅。
MessagingCenter.Subscribe<INotifier, AlertModel> (this, "myalert",
(s,arg) => { //Handle });
我的问题是我如何获得页面的现有实例,而不是每次都创建一个新的实例?或者,如果在处理页面方面有最佳做法 - 我应该让所有页面都有某种单身或某种东西吗?或者以其他方式解决这个问题?
问题似乎是,您在应用程序的生命周期(通常是android设备一直重启设备)中多次订阅。因此,在退出时退订或在应用程序生命周期中确保代码被调用一次。 – Stefan
什么是最好的做法/一个很好的模式,只在应用程序的一生中订阅一次?某种订阅的静态目录?或者你会保持链接到更密切处理它的类/页面? – MartinM