如何使用MvvmCross 5 IMvxNavigationService获取PendingIntent?

Tre*_*com 6 c# xamarin.android mvvmcross

我有一个我在MvvmCross 4.x中使用的方法,用于NotificationCompat.Builder设置PendingIntent一个通知,以便在用户单击通知时显示ViewModel.我正在尝试将此方法转换为使用MvvmCross 5.x,IMvxNavigationService但无法查看如何设置演示文稿参数,并获得PendingIntent使用新的导航API.

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);
}
Run Code Online (Sandbox Code Playgroud)

当我点击该通知,但RouteNotificationViewModel确实出现PrepareInitialize没有被调用.有什么必要将此方法从MvvmCross 4.x导航风格转换为MvvmCross 5.x导航风格?

Tre*_*com 0

在 MvvmCross 5+ 中可以做到这一点,但它不像以前那么干净。

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

[Activity(LaunchMode = LaunchMode.SingleTop, ...)]
public class MainActivity : MvxAppCompatActivity
Run Code Online (Sandbox Code Playgroud)

像这样生成通知 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);
Run Code Online (Sandbox Code Playgroud)

现在有两个地方可以处理来自 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果应用程序在单击通知时正在运行,则将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.
    }
}
Run Code Online (Sandbox Code Playgroud)