当应用程序在后台运行时如何正确通知有关推送通知的当前视图模型

时间:2019-02-14 10:42:04

标签: c# xamarin push-notification xamarin.android mvvmcross

我正在使用Xamarin和MvvmCross开发适用于iOS和Android平台的手机应用程序。在Android版本中,在这两种情况下,我可以在应用程序处于前台状态和关闭状态时接收推送通知,并导航到所需的视图模型。

当应用程序处于后台并且由于用户在推送通知中轻按而恢复时,我无法从启动屏幕导航到特定视图模型。

我可以保留一个标志,然后检查是否设置了该标志并恢复导航,然后恢复每个视图模型,但是我真的不喜欢该解决方案,而是想像在应用程序运行时一样使用事件在前台。问题在于,当应用程序在后台运行并从推送通知中恢复时,我的事件仍未分配给其处理程序。

这是我的代码。 SplashScreen:

public class SplashScreen : MvxSplashScreenAppCompatActivity
{
    private bool _setPushNotificationHint;
    private Dictionary<string, string> _pushNotificationData;

    public SplashScreen() : base(Resource.Layout.SplashScreenLayout)
    {
    }
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        if (Intent.Extras != null)
        {
            _pushNotificationData = new Dictionary<string, string>();
            foreach (var key in Intent.Extras.KeySet())
            {
                var value = Intent.Extras.Get(key);
                if(value != null)
                {
                    _pushNotificationData.Add(key, value.ToString());
                }                   
            }
            _setPushNotificationHint = true;
        }

        //avoid showing splash screen when resuming app pressing app icon or when tapping on push notification
        if (!IsTaskRoot)
        {
            //deliver notification only when app is started and is in background. When it's closed we'll use GetAppStartHint
            if (_setPushNotificationHint)
            {
                PushNotificationManager.OnMessageReceivedAppInBackground(this, _pushNotificationData);
            }
            Finish();
            return;
        }
        //just initialize essentials when first start of the app, not when splash screen is shown
        Xamarin.Essentials.Platform.Init(this, bundle);
    }

在这里,我可以获取推送通知信息并触发我的PushNotificationManager,从而触发事件。这是它的一部分:

public class PushNotificationManager : IPushNotification
{
    public const string controlIdKey = "controlId";

    private static PushNotificationDataEventHandler _onNotificationReceived;
    public event PushNotificationDataEventHandler OnNotificationReceived
    {
        add
        {
            _onNotificationReceived += value;
        }
        remove
        {
            _onNotificationReceived -= value;
        }
    }

    private static PushNotificationDataEventHandler _onNotificationReceivedWhileForeground;
    public event PushNotificationDataEventHandler OnNotificonReceivedWhileForegroundationReceived
    {
        add
        {
            _onNotificationReceivedWhileForeground += value;
        }
        remove
        {
            _onNotificationReceivedWhileForeground -= value;
        }
    }

    /// <summary>
    /// Handles an incoming push notification in Android when app is in Foreground.
    /// </summary>
    /// <param name="remoteMessage">User info.</param>
    public static void OnMessageReceived(RemoteMessage remoteMessage)
    {
        var notification = CreateNotificationFromRemoteMessage(remoteMessage);
        _onNotificationReceivedWhileForeground?.Invoke(CrossPushNotification.Instance, new PushNotificationDataEventArgs(notification));
    }

    /// <summary>
    /// When app is in background in Android, we get to the splashscreen, who will call this method to publish a NotificationMessage to the interested ViewModels
    /// </summary>
    /// <param name="sender">Sender.</param>
    /// <param name="parameters">Parameters.</param>
    public static void OnMessageReceivedAppInBackground(object sender, Dictionary<string, string> parameters)
    {
        var notification = CreateNotificationFromIntentExtras(parameters);
        //we need to publish a message instead of rising an event because this is triggered from the splash screen and the view model 
        //Mvx.IoCProvider.Resolve<IMvxMessenger>().Publish(notificationMessage);
        //_onNotificationReceived?.Invoke(CrossPushNotification.Instance, new PushNotificationDataEventArgs(notification));
        //todo find a way to properly notify the current view to navigate to the device details view model
    }

    /// <summary>
    /// In Android plataform, we create the notification from the parameters received in the splashscreen as intent extras
    /// </summary>
    /// <returns>The notification from intent extras.</returns>
    /// <param name="parameters">Parameters.</param>
    private static Notification CreateNotificationFromIntentExtras(Dictionary<string, string> parameters)
    {
        parameters.TryGetValue(controlIdKey, out var controlId);

        return new Notification
        {
            ControlId = controlId
        };
    }

然后在BaseViewModel.cs中,我附加应从PushNotificationManager触发的事件的处理程序:

public override void ViewAppeared()
    {
        base.ViewAppeared();
        //_token = Mvx.IoCProvider.Resolve<IMvxMessenger>().Subscribe<NotificationMessage>(OnNotificaitonMessage);
        CrossPushNotification.Instance.OnNotificationReceived += NotificationReceived;
        CrossPushNotification.Instance.OnNotificonReceivedWhileForegroundationReceived += NotificationInForegroundReceived;
    }

    public override void ViewDisappeared()
    {
        base.ViewDisappeared();
        //Mvx.IoCProvider.Resolve<IMvxMessenger>().Unsubscribe<NotificationMessage>(_token);
        CrossPushNotification.Instance.OnNotificationReceived -= NotificationReceived;
        CrossPushNotification.Instance.OnNotificonReceivedWhileForegroundationReceived -= NotificationInForegroundReceived;
    }

    public override void ViewDestroy(bool viewFinishing = true)
    {
        //Mvx.IoCProvider.Resolve<IMvxMessenger>().Unsubscribe<NotificationMessage>(_token);
        CrossPushNotification.Instance.OnNotificationReceived -= NotificationReceived;
        CrossPushNotification.Instance.OnNotificonReceivedWhileForegroundationReceived -= NotificationInForegroundReceived;
        base.ViewDestroy(viewFinishing);
    }

但是当应用来自后台时,这些事件处理程序为null,因为视图尚未出现。我无法在构造函数中附加事件的处理程序,因为当视图消失时,我无法将其删除。只有当前的视图模型才应处理事件并导航到我所需的视图模型。

我也尝试了MvxMessenger插件,但没有成功。

所以我的问题是,当应用程序在后台运行时,如何正确通知视图模型有推送通知?

0 个答案:

没有答案