c# - 如何使用MvvmCross 5 IMvxNavigationService获取PendingIntent?

原文 标签 c# xamarin.android mvvmcross

我在mvvmcross 4.x中使用了一个方法,该方法与NotificationCompat.Builder一起用于设置通知的PendingIntent以在用户单击通知时显示viewmodel。我试图将此方法转换为使用mvvmcross 5.xIMvxNavigationService但看不到如何设置表示参数,也看不到如何使用新的导航api获取PendingIntent

private PendingIntent RouteNotificationViewModelPendingIntent(int controlNumber, RouteNotificationContext notificationContext, string stopType)
{
    var request = MvxViewModelRequest<RouteNotificationViewModel>.GetDefaultRequest();
    request.ParameterValues = new Dictionary<string, string>
    {
        { "controlNumber", controlNumber.ToString() },
        { "notificationContext", notificationContext.ToString() },
        { "stopType", stopType }
    };
    var translator = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator>();
    var intent = translator.GetIntentFor(request);
    intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

    return PendingIntent.GetActivity(Application.Context,
                                     _notificationId,
                                     intent,
                                     PendingIntentFlags.UpdateCurrent);
}

当我单击通知时,RouteNotificationViewModel确实出现,但未调用PrepareInitialize。将此方法从MVVMcross 4.x导航样式转换为MVVMcross 5.x导航样式需要什么?

最佳答案

在mvvmcross 5+中可以做到这一点,但它不像以前那样干净。
对于初学者,您需要为活动指定单顶启动模式:

[Activity(LaunchMode = LaunchMode.SingleTop, ...)]
public class MainActivity : MvxAppCompatActivity

生成如下挂起的通知内容:
var intent = new Intent(Context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.SingleTop);
// Putting an extra in the Intent to pass data to the MainActivity
intent.PutExtra("from_notification", true);
var pendingIntent = PendingIntent.GetActivity(Context, notificationId, intent, 0);

现在,在仍然允许使用MVVMcross导航服务的情况下,有两个地方可以从mainActivity处理此意图:
如果在单击通知时应用程序未运行,则将调用OnCreate
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    if (bundle == null && Intent.HasExtra("from_notification"))
    {
        // The notification was clicked while the app was not running. 
        // Calling MvxNavigationService multiple times in a row here won't always work as expected. Use a Task.Delay(), Handler.Post(), or even an MvvmCross custom presentation hint to make it work as needed.
    }
}

如果在单击通知时应用程序正在运行,则将调用OnNewIntent
protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);
    if (intent.HasExtra("from_notification"))
    {
        // The notification was clicked while the app was already running.
        // Back stack is already setup.
        // Show a new fragment using MvxNavigationService.
    }
}

相关文章:

c# - 空间winforms控件

c# - 如何在WPF中在 Canvas 上移动形状?

c# - 流利的绑定(bind)和UIButton标题

xamarin.forms - 创建View-ViewModel查找表时出现问题-您为ViewModels注册了多个 View

c# - Android应用程式太大,无法建立连结

android - MvvmCross绑定(bind)+ Android EventHandler

c# - WPF客户端无法捕获来自WCF的自定义异常

c# - 将多个csv文件作为单个数据集加载的最佳方法

android - 在Xamarin.android中获取小吃店的高度

android - Xamarin iOS / Android:如何在运行应用程序时删除屏幕截图