我的想法是利用PutExtra https://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/结合消息中心 https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/.
首先,在通知栏中显示通知:
Intent intent = new Intent(Forms.Context, typeof(MainActivity));
if (openPage)
{
intent.SetFlags(ActivityFlags.SingleTop);
intent.PutExtra("OpenPage", "SomePage");
}
const int pendingIntentId = 0;
PendingIntent pendingIntent = PendingIntent.GetActivity(Forms.Context, pendingIntentId, intent, PendingIntentFlags.OneShot);
var nMgr = (NotificationManager)Android.App.Application.Context.GetSystemService(Context.NotificationService);
Notification.Builder notBuilder = new Notification.Builder(Android.App.Application.Context)
.SetContentIntent(pendingIntent)
.SetContentTitle("SomeApp")
.SetContentText(message)
.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetAutoCancel(true);
var notification = notBuilder.Build();
nMgr.Notify(0, notification);
In MainActivity.cs您检查额外的内容:
protected override void OnNewIntent(Intent intent)
{
// Send message to the PCL (XF) if a certain page should be opened.
if (intent.HasExtra("OpenPage"))
{
string pageName = intent.GetStringExtra("OpenPage") ?? "None";
if (pageName != "None")
{
var message = new OpenPageMessage { PageName = pageName };
MessagingCenter.Send(message, Message.Msg_OpenPage);
}
}
base.OnNewIntent(intent);
}
以及您的中央导航实例(例如MainPage
),订阅此消息:
MessagingCenter.Subscribe<Message.OpenPageMessage>(this, Message.Msg_OpenPage, (async) message =>
{
// Loads a certain page if a message is received
switch (message.PageName)
{
case "SomePage":
await Navigation.PushModalAsync(new SomePage(), true);
break;
default:
break;
}
});
另外,这是我的消息.cs:
public class Message
{
public const string Msg_OpenPage = "OpenPage";
public class OpenPageMessage {
public string PageName { get; set; }
}
}
借助这个source https://stackoverflow.com/a/44964328/426227.
Edit
如果您一次有多个推送通知,并且通知被覆盖,则会出现问题。人们可以使用不同的requestCode https://developer.android.com/reference/android/app/PendingIntent.html#getActivity(android.content.Context,%20int,%20android.content.Intent,%20int) or use FLAG_UPDATE_CURRENT https://developer.android.com/reference/android/app/PendingIntent.html#FLAG_UPDATE_CURRENT.