问题
I'm relatively new to Xamarin and have gotten to a point in my application where I want to have notifications, I'm using local notifications to show the user that they have received a message from someone in my application. While I can get the notification to show, when it clicks it either shows nothing or it "restarts" the application (takes the user back to the login page).
How do I get the notification to show a set page, such as my contacts page when the notification is clicked on?
回答1:
How do I get the notification to show a set page, such as my contacts page when the notification is clicked on?
Xamarin.Forms
only has one activity, no matter how many pages you created, they are created on MainActivity
.
But still we can have a workaround to work it out:
Create your local notification with an intent to indicate which page you want to navigate to(
Page1
):Notification.Builder builder = new Notification.Builder(Xamarin.Forms.Forms.Context); Intent intent = new Intent(Xamarin.Forms.Forms.Context, typeof(MainActivity)); Bundle bundle = new Bundle(); // if we want to navigate to Page1: bundle.PutString("pageName", "Page1"); intent.PutExtras(bundle); PendingIntent pIntent = PendingIntent.GetActivity(Xamarin.Forms.Forms.Context, 0, intent, 0); builder.SetContentTitle(title) .SetContentText(text) .SetSmallIcon(Resource.Drawable.icon) .SetContentIntent(pIntent); var manager = (NotificationManager)Xamarin.Forms.Forms.Context.GetSystemService("notification"); manager.Notify(1, builder.Build());
In
MainActivity.cs
insideOnCreate
we use reflection to set the App'sMainPage
:protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); var myApp = new App(); var mBundle = Intent.Extras; if (mBundle != null) { var pageName = mBundle.GetString("pageName"); if (!string.IsNullOrEmpty(pageName)) { //get the assemblyQualifiedName of page var pageAssemblyName = "Your_PCL_Name." + pageName+",Your_PCL_Name"; Type type = Type.GetType(pageAssemblyName); if (type != null) { var currentPage = Activator.CreateInstance(type); //set the main page myApp.MainPage = (Page)currentPage; } } } //load myApp LoadApplication(myApp); }
Notes: this workaround modifies the MainPage
of your PCL's App
, if you have usage for this property, please modify the logic properly.
来源:https://stackoverflow.com/questions/47459995/show-contentpage-that-called-local-notification-when-notification-is-clicked