我正在使用Xamarin和MvvmCross创建一个跨平台的应用程序。MvvmCross + Android notifcation点击获取viewmodel为空
在android平台上,我需要显示通知。
通知点击用户应登陆到MainView屏幕。一切都按要求运作。
当应用程序从后台移除,然后通知到达并且用户单击通知,然后MainViewModel为空时,就会出现问题。
下面是我如何显示通知。
private void NotifyNotification(string title, string message)
{
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
int unique = 1;
//uiIntent
Intent uiIntent;
uiIntent = new Intent(this, typeof(MainView));
uiIntent.PutExtra("AppNotification", true);
uiIntent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
//pendingIntent
var pendingIntent = PendingIntent.GetActivity(this, 0, uiIntent, PendingIntentFlags.OneShot);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
Notification notification = builder.SetContentIntent(pendingIntent)
.SetSmallIcon(Resource.Drawable.notificationIcon).SetTicker(message)
.SetAutoCancel(true).SetContentTitle(title).SetNumber(DroidConstants.NotifyCounter)
.SetDefaults((int)NotificationDefaults.All)
.SetContentText(message).Build();
notificationManager.Notify(unique, notification);
}
下面是我的MainView类代码
public abstract class BaseMainView : BaseView<MainViewModel>
{
}
[Activity(Label = "New Tasks",
NoHistory = false,
Icon = "@drawable/icon",
Theme = "@style/Theme.AppCompat.Light",
LaunchMode = Android.Content.PM.LaunchMode.SingleTask,//setted to single task to handle stack issue
//ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait,
UiOptions = Android.Content.PM.UiOptions.SplitActionBarWhenNarrow)]
/*,
ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize*/
public class MainView : BaseMainView
{
public new MainViewModel ViewModel
{
get { return base.ViewModel; }
set { base.ViewModel = value; }
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set up View to be shown
SetContentView(Resource.Layout.MainView);
var set = this.CreateBindingSet<MainView, MainViewModel>();
//Code to map binding with controls
set.Apply();
}
protected override void OnNewIntent(Android.Content.Intent intent)
{
//When is in background or running then this get called and I simple perform the action required.
}
}
注: - 我已经设置好的这个活动的LaunchMode是SingleTask。
LaunchMode = Android.Content.PM.LaunchMode.SingleTask
因为,当该应用是前景或通知点击OnNewIntent背景被调用,并能够在那里执行逻辑。但是,当应用程序从后台删除,并通知到达然后通知单击OnCreate方法被调用,那里我得到的MainViewModel为空。
请帮我解决这个问题。
感谢, Aaman