我有一個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