单击通知时显示调用本地通知的内容页面

Show contentpage that called local notification when notification is clicked

我对 Xamarin 比较陌生,并且在我的应用程序中已经到了我想要通知的地步,我正在使用本地通知向用户显示他们已经收到来自我应用程序中某人的消息。虽然我可以让通知显示,但当它单击时,它要么什么都不显示,要么 "restarts" 应用程序(将用户带回登录页面)。

如何让点击通知时显示设置页面的通知,比如我的联系人页面?

How do I get the notification to show a set page, such as my contacts page when the notification is clicked on?

Xamarin.Forms只有一个activity,无论你创建了多少页,它们都是在MainActivity上创建的。

但我们仍然可以找到解决方法:

  1. 创建您的本地通知以指示您要导航到哪个页面(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());
    
  2. MainActivity.cs里面OnCreate我们使用反射来设置App的MainPage:

    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);
    }
    

注意:此解决方法修改了 PCL 的 AppMainPage,如果您对此 属性 有使用,请正确修改逻辑。