您不必为您的平台项目添加任何接口,只需将 nuget 包安装到两个项目 Android/IOS。
在 IOS 上,您应该添加:
// Ask the user for permission to get notifications on iOS 8.0+
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
var settings = UIUserNotificationSettings.GetSettingsForTypes (
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet ());
UIApplication.SharedApplication.RegisterUserNotificationSettings (settings);
}
到你的方法:
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
在 AppDelegate 中:
然后在您的共享项目中调用:
using Plugin.LocalNotifications.Abstractions;
CrossLocalNotifications.Current.Show("You've got mail", "You have 793 unread messages!");
在替换当前页面时,您无需执行任何操作,Xamarin Forms 将为您处理。
同样在 android 上,您可以通过设置 MainActivity 的 LaunchMode 来控制应用程序的重新启动行为:
例子:
LaunchMode = Android.Content.PM.LaunchMode.SingleInstance, AlwaysRetainTaskState = true
要了解有关 Android 上的 LauchModes 的更多信息,请阅读:
https://developer.android.com/guide/components/tasks-and-back-stack.html
并检查其他活动标志:
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_SINGLE_TOP
目前此插件不允许在应用程序内捕获任何通知。但是您可以通过使用特定于平台的功能来做到这一点
IOS:请参考
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/ios/remote_notifications_in_ios/
public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
{
MessagingCenter.Send<MainPage> (this, "IOS notification received");
}
Android:在阅读了这个插件的源代码后,我发现,您可以在您的 on create 方法中检查 Bundle 以获取键 ScheduledAlarmHandler.LocalNotificationKey
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
if(bundle.ContainsKey(ScheduledAlarmHandler.LocalNotificationKey)){
//App launched form notification
MessagingCenter.Send<MainPage> (this, "Android notification received");
}
}
您也可以尝试使用 BroadcastReceiver 类;
https://developer.xamarin.com/api/type/Android.Content.BroadcastReceiver/