如何使用MvvmCross 5 IMvxNavigationService获取PendingIntent?

问题描述 投票:5回答:1

我有一个我在MvvmCross 4.x中使用的方法,它与NotificationCompat.Builder一起用来设置通知的PendingIntent,以便在用户点击通知时显示ViewModel。我正在尝试将此方法转换为使用MvvmCross 5.x IMvxNavigationService,但无法查看如何设置演示参数,并使用新的导航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导航风格?

c# xamarin.android mvvmcross
1个回答
0
投票

可以在MvvmCross 5+中执行此操作,但它不像以前那样干净。

对于初学者,您需要为活动指定singleTop启动模式:

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

生成通知PendingIntent,如下所示:

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);

现在有两个地方可以从MainActivity处理此Intent,同时仍允许使用MvvmCross导航服务:

如果在点击通知时应用程序未运行,则将调用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.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.