我在mvvmcross 4.x中使用了一个方法,该方法与NotificationCompat.Builder
一起用于设置通知的PendingIntent
以在用户单击通知时显示viewmodel。我试图将此方法转换为使用mvvmcross 5.xIMvxNavigationService
但看不到如何设置表示参数,也看不到如何使用新的导航api获取PendingIntent
。
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);
}
当我单击通知时,RouteNotificationViewModel确实出现,但未调用
Prepare
和Initialize
。将此方法从MVVMcross 4.x导航样式转换为MVVMcross 5.x导航样式需要什么?
最佳答案
在mvvmcross 5+中可以做到这一点,但它不像以前那样干净。
对于初学者,您需要为活动指定单顶启动模式:
[Activity(LaunchMode = LaunchMode.SingleTop, ...)]
public class MainActivity : MvxAppCompatActivity
生成如下挂起的通知内容:
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);
现在,在仍然允许使用MVVMcross导航服务的情况下,有两个地方可以从mainActivity处理此意图:
如果在单击通知时应用程序未运行,则将调用
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.
}
}
如果在单击通知时应用程序正在运行,则将调用
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.
}
}