MvvmCross: Handling notification clicks.

MvvmCross: Handling notification clicks.

Handling local notifications in Android is different as in iOS, so that code is non cross platform. On MvvmCross I like to handle that kind of scenarios in a custom Plugin, but this time, to keep the post very short I will handle it in the Activity that raised the notification. 

 

Let's say that we want to show a notification when something happens in our application and then, redirect the user to a custom ViewModel. 

void SetBackgroundAlert(Route route) {
    var intent = GetRouteViewIntent(route);
    var pendingItent = 
       PendingIntent.GetActivity(this, 0,intent, PendingIntentFlags.UpdateCurrent);

    var notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
    var notification = new Notification.Builder(this)
        .SetContentTitle("Alarm").SetContentText(RouteView.offRouteMessage)
        .SetContentIntent(pendingItent)
        .SetSmallIcon(Resource.Drawable.notification_icon).Notification;
        notificationManager.Notify(1, notification);
        
        }

Nothing new here, we just created a notification from the notification builder, the key is the method GetRouteViewIntent. We retrieved a specific intent which will be passed to the PendingIntent, then when the user clicks on the notification, it will be redirect to our ViewModel. The method GetRouteViewIntent looks as follows:

 

static Intent GetRouteViewIntent(Route route) {
     var request = new MvxViewModelRequest();
     request.ParameterValues = new System.Collections.Generic.Dictionary<stringstring>();                        
     request.ParameterValues.Add("idRoute", route.IdRoute.ToString());
     request.ViewModelType = typeof(RouteViewModel);
     var requestTranslator = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator>();
     return requestTranslator.GetIntentFor(request);
        }

 

We just created a request (with its parameters) and then we created our intent like MvvmCross internally does.