MvvmCross在Android通知点击导航到ViewModel

时间:2016-02-18 17:18:59

标签: android xamarin mvvmcross

我使用Support.V7.NotificationCompat显示通知。我想在单击此通知时导航到ViewModel。当我尝试使用MvxViewModelRequest显示ViewModel时,我传递给ViewModel的导航参数不起作用,但是当我像这样使用ShowViewModel时它可以工作:

ShowViewModel<RouteModificationViewModel>(new { id = existingModification.Id });

这是ViewModel Init方法。当我使用ShowViewModel导航时,Guid具有正确的值。当我使用Guid.Empty导航时,Guid的值始终为MvxViewModelRequest(全部为0&#39; s。)

public void Init(Guid id)
{
    _routeModificationId = id;
}

这就是我尝试从通知中显示ViewModel的方式:

public void ShowRouteModifiedNotification(RouteModificationModel routeModificationModel)
{
    var context = Application.Context;
    var builder = new NotificationCompat.Builder(context);
    builder.SetDefaults(NotificationCompat.DefaultAll);
    builder.SetCategory(NotificationCompat.CategoryStatus);
    builder.SetAutoCancel(true);
    builder.SetPriority(NotificationCompat.PriorityHigh);
    builder.SetSmallIcon(Resource.Mipmap.ic_launcher);
    builder.SetContentTitle("Route Modification");
    builder.SetContentText("Hello, World!");
    builder.SetContentIntent(GetIntent(routeModificationModel.Id));
    builder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
    builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
    var notification = builder.Build();
    var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
    var handler = new Handler(Looper.MainLooper);
    handler.Post(() =>
    {
       notificationManager.Notify(RouteModificationNotificationId, notification);
    });
}

private PendingIntent GetIntent(Guid guid)
{
    var request = MvxViewModelRequest<RouteModificationViewModel>.GetDefaultRequest();
    var json = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(new { id = guid });
    request.PresentationValues = new Dictionary<string, string>
    {
        { "id", json }
    };
    var translator = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator>();
    var intent = translator.GetIntentFor(request);
    return PendingIntent.GetActivity(Application.Context, 0, intent, 0);
}

任何人都可以看到我错过或做错了吗?

1 个答案:

答案 0 :(得分:1)

MvvmCross此后收到了MvvmCross 5.0及更高版本中导航工作方式的重大更新。如果您使用的是MvvmCross 4.x或3.x,则此问题可能才有意义。在这种情况下,4.x中的MvvmCross导航API未正确序列化Guid。您可以通过将Guid序列化为字符串并将字符串作为导航参数传递,然后将字符串反序列化为ViewModel中的Guid来解决此问题。