Using Notifications on android with MvvmCross

2019-03-26 19:11发布

问题:

I do want to create a plugin which does implement something like a notification-service.

So what I'm doing at the moment is something like this:

        var activity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity;
        var builder = new NotificationCompat.Builder(activity.ApplicationContext)
            .SetContentTitle(title)
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentText(message);
        var notificationManager = (NotificationManager)activity.ApplicationContext.GetSystemService(Context.NotificationService);
        notificationManager.Notify(0, builder.Build());

This works fine and does show the notification as it should show. Next step is, that I want to navigate from the notification to my activity. Which means in MvvmCross I do want to navigate to my ViewModel.

But how do I now pack the ShowViewModel<...>()-Command into this notification? Is this even possible?

On native android I would create a PendingIntent which does point to my Activity I want to show.

Any idea? Hint? Tip? :-)

回答1:

The default MvvmCross presenter on Android uses Intents for navigation. These are generated by the method Intent GetIntentFor(MvxViewModelRequest request) in the IMvxAndroidViewModelRequestTranslator interface.

By default this is implemented within: MvxAndroidViewsContainer.cs#L117

    public virtual Intent GetIntentFor(MvxViewModelRequest request)
    {
        var viewType = GetViewType(request.ViewModelType);
        if (viewType == null)
        {
            throw new MvxException("View Type not found for " + request.ViewModelType);
        }

        var converter = Mvx.Resolve<IMvxNavigationSerializer>();
        var requestText = converter.Serializer.SerializeObject(request);

        var intent = new Intent(_applicationContext, viewType);
        intent.PutExtra(ExtrasKey, requestText);

        AdjustIntentForPresentation(intent, request);

        intent.AddFlags(ActivityFlags.NewTask);
        return intent;
    }

If you need to generate Intents for other purposes (e.g. in order to then go on and generate PendingIntents) then you can Resolve and call this interface yourself.

    var request = MvxViewModelRequest<MyViewModel>.GetDefaultRequest();
    request.PresentationValues = new Dictionary<string, string>() {
       { "life", "42" }
    };
    var translator = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator>();
    var intent = translator.GetIntentFor(request);
    var pending = PendingIntent.GetActivity (context, 0, intent, 0);

For further information on generating MvxViewModelRequest objects, see also the overloaded ShowViewModel methods in MvxNavigatingObject.cs