Mvvmcross Android 通知将参数传递给现有的 ViewModel

Mvvmcross Android Notification Pass Parameter to Existing ViewModel

我有一个带通知的前台服务。当用户点击通知时,它会将用户带回主屏幕视图模型(或者如果卸载则重新加载)。

我想在通知中添加 2 个操作(暂停、停止)。最好用一个参数来调用同一个viewmodel来指明action类型,让主屏幕viewmodel来处理这个action。由于主屏幕视图模型可能已经加载,因此不会执行更多初始化。像显示 viewmodel 这样传递参数是行不通的。现有的视图模型并不知道它确实是由通知触发的。

如何将每个动作类型的不同参数传递给视图模型,并在视图模型中检索它以进行相应的操作?或者应该以不同的方式完成?

这是通知的代码:

                var request = MvxViewModelRequest<RouteLayoutViewModel>.GetDefaultRequest();
                var intent = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator>().GetIntentFor(request);
                const int pendingIntentId = 0;
                PendingIntent pendingIntent = PendingIntent.GetActivity(Application.Context, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent);

                var builder = new NotificationCompat.Builder(this);

                builder
                    .SetContentTitle(AppConstants.AppName)
                    .SetContentText("notification_text")
                    .SetSmallIcon(Resource.Drawable.Icon)
                    .SetContentIntent(pendingIntent); ..........

                var notification = builder.Build();

                StartForeground(AppConstants.SERVICE_RUNNING_NOTIFICATION_ID, notification);

谢谢,

尼克

MvvmCross 5 更改了 ViewModel 参数在内部序列化的方式。 MvvmCross 5 尚未更新以处理这种情况 AFAIK。下面是一些示例代码,演示了如何使用当前的 BroadcastReceiver 解决该问题。这种方法将允许您在用户单击 Android 通知后使用参数进行导航。

当您构建通知时:

var intent = new Intent(context, typeof(YourBroadcastReceiver));
intent.SetAction("YOUR_ACTION");
// Put your other parameters here...
intent.PutExtra("id", id);
var pendingIntent = PendingIntent.GetBroadcast(context, _notificationId, intent, PendingIntentFlags.UpdateCurrent);
...
notificationBuilder.SetContentIntent(pendingIntent);

然后像这样添加一个 BroadcastReceiver class:

[BroadcastReceiver]
public class YourBroadcastReceiver : MvxBroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == "YOUR_ACTION")
        {
            // TODO: Extract the contents from the intent.
            var id = intent.GetIntExtra("id", 0);
            // TODO: Navigate using IMvxNavigationService using the parameters pulled from the Intent.
        }
    }
}