MvvmCross-如何从通知启动应用程序

问题描述

我正在使用MvvmCross 6.4.3。

如果该应用未运行,并且我单击了以前从该应用收到的通知,则该应用不会转到首页(在我的情况下是登录页面

在我的自定义MvxAppStart中调用了由用户启动的应用程序NavigatetoFirstviewmodel时,它随后将调用MvxApplication.Startup。

但是,当我尝试从通知中启动应用程序时,这些都没有被调用,因此不会显示我的第一页。

我应该在哪里将代码导航到第一页,以便仅在从通知开始的情况下调用

解决方法

我不得不手动执行此操作。不知道这是否是官方方式,但我也没有发现其他人是怎么做到的。

  • 应用打开并显示通知点击。
  • 在“活动” OnCreate方法中,检查Intent中是否有其他通知。如果它包含通知,则说明您已经通过单击通知来启动它。
  • 确保已设置应用。
var setupSingleton = MvxAndroidSetupSingleton.EnsureSingletonAvailable(this);
setupSingleton.EnsureInitialized();
  • 导航到所需的起始页面。
,

这就是我的做法。我已将其发布在Github上:

对于初学者,您想为活动指定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导航服务:

  1. OnCreate-如果在单击通知时应用未运行,则将调用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.
        var mvxNavigationService = MvvmCross.Mvx.IoCProvider.Resolve<IMvxNavigationService>();
        await mvxNavigationService.Navigate<ViewModel>();
        var handler = new Handler(Looper.MainLooper);
        handler.Post(async () => await mvxNavigationService.Navigate<AnotherViewModel>();
    }
}
  1. OnNewIntent-如果在单击通知时应用程序正在运行,则将调用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.
    }
}