You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Android应用后台/被杀死时点击推送如何跳转内容页展示消息

问题根因分析

  1. 当前你使用的推送payload同时包含notification和data字段,属于通知消息类型:应用在后台/被杀死时,这类通知会由系统FCM服务直接弹出,不会触发你自定义的OnMessageReceived方法,你代码里写的带跳转参数的PendingIntent根本不会生效,点击系统弹出的通知默认只会启动应用,不会携带自定义参数。
  2. 现有代码还存在逻辑疏漏:
    • SplashActivity的OnCreate用了带PersistableBundle的特殊重载,只有设置了persistableMode属性才会调用,应用冷启动时读参数的逻辑根本不会执行
    • MainActivity没有重写OnNewIntent,应用后台存活时点击通知不会走OnCreate,新的Intent参数无法被捕获
    • 本地通知的PendingIntent跳转目标和启动页路由逻辑冲突

修复步骤

1. 修改Azure推送payload结构

去掉notification字段,改成纯数据消息,保证不管应用前后台,推送都会触发OnMessageReceived走自定义通知逻辑:

{
    "data":{
        "title":"Notification Hub Test Notification",
        "body":"This is a sample notification delivered by Azure Notification Hubs.",
        "property1":"value1",
        "property2":42
    }
}

同步修改OnMessageReceived的参数读取逻辑:

public override void OnMessageReceived(RemoteMessage message)
{
    base.OnCreate(savedInstanceState);            
    string title = message.Data.ContainsKey("title") ? message.Data["title"] : "myapp";
    string body = message.Data.ContainsKey("body") ? message.Data["body"] : message.Data.Values.First();
    SendLocalNotification(title, body);
    // 前台场景直接更新页面
    if (App.Current != null)
    {
        (App.Current.MainPage as DOTFORMS3.Views.MSG)?.AddMessage(body);
    }
}

调整SendLocalNotification方法支持传入标题,设置到通知的ContentTitle即可。

2. 修复SplashActivity的参数读取逻辑

把特殊的OnCreate重载换成标准版本:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);            
    string message = Intent.GetStringExtra("message");
    if (message == null)
    {
        LoadApplication(new App(false));
    }
    else
    {
        App.message = message;
        LoadApplication(new App(true));
    }
    IsPlayServicesAvailable();
    CreateNotificationChannel();    
}

3. 调整PendingIntent跳转目标

应用冷启动必须走SplashActivity,修改SendLocalNotification里的Intent配置:

var intent = new Intent(this, typeof(splashactivity));
intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
intent.PutExtra("message", body);
// 把随机requestCode改成固定值,flag换成UpdateCurrent避免参数丢失
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);

4. 新增MainActivity的OnNewIntent逻辑

处理应用后台存活时的通知跳转:

protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);
    Intent = intent;
    string message = intent.GetStringExtra("message");
    if (!string.IsNullOrEmpty(message))
    {
        // 应用已启动时直接跳转到目标页
        App.Current.MainPage = new NavigationPage(new DOTFORMS3.Views.MSG(message));
    }
}

内容的提问来源于stack exchange,提问作者XAMMOT2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:15:02