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

如何在Android上通过OneSignal唤醒后台中的.NET MAUI应用?

.NET MAUI集成OneSignal:后台唤醒应用解决方案

可以唤醒处于后台状态的应用,但Android和iOS平台有不同的权限限制与实现逻辑,以下针对你的代码和场景给出具体修正方案:

Android平台处理

你的NotificationServiceExtension代码存在两个核心问题:一是Android 10+对后台启动Activity有严格限制,直接调用StartActivity大概率会被系统拦截;二是未正确利用OneSignal通知的点击意图来触发应用唤醒。

1. 确保服务注册正确

首先在AndroidManifest.xml中注册你的通知扩展服务:

<service android:name="my.namespace.ExampleNotification"
         android:permission="android.permission.BIND_JOB_SERVICE">
    <intent-filter>
        <action android:name="com.onesignal.NotificationServiceExtension" />
    </intent-filter>
</service>

2. 修正后台状态判断逻辑

在MAUI的App.xaml.cs中维护准确的应用前后台状态:

public static bool IsAppInBackground { get; set; }

protected override void OnStart()
{
    IsAppInBackground = false;
}

protected override void OnSleep()
{
    IsAppInBackground = true;
}

protected override void OnResume()
{
    IsAppInBackground = false;
}

3. 修改通知处理代码

放弃后台直接启动Activity的方式,改为修改通知的点击意图,让用户点击通知时自动唤醒应用(这是Android系统允许的合规方式):

[Service(Name = "my.namespace.ExampleNotification")]
public class NotificationServiceExtension : Java.Lang.Object, INotificationServiceExtension
{
    public void OnNotificationReceived(INotificationReceivedEvent e)
    {
        var currentNotification = e.Notification;
        
        if (!App.IsAppInBackground)
        {
            e.PreventDefault();
            // 应用在前台,可直接处理通知内容(比如显示弹窗、更新UI)
        }
        else
        {
            // 创建打开MainActivity的意图
            var launchIntent = new Intent(Application.Context, typeof(MainActivity));
            launchIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop | ActivityFlags.NewTask);
            
            // 创建PendingIntent,确保点击通知时触发
            var pendingIntent = PendingIntent.GetActivity(
                Application.Context, 
                0, 
                launchIntent, 
                PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
            
            // 更新通知的点击行为
            currentNotification.ClickAction.Action = "ACTION_LAUNCH_APP";
            currentNotification.ClickAction.Intent = pendingIntent;
            
            // 提交修改后的通知,用户点击后会唤醒应用
            e.Notification = currentNotification;
        }
    }
}

如果一定要实现自动唤醒(无需用户点击),需要额外操作:

  • 申请REQUEST_IGNORE_BATTERY_OPTIMIZATIONS权限,引导用户将应用加入电池优化白名单
  • 确保应用当前运行前台服务(Android系统仅允许前台服务在后台启动Activity)

iOS平台处理

iOS对后台唤醒的限制更严格,常规推送无法自动唤醒后台应用,只能通过以下方式实现:

  1. 在Info.plist中开启Background modes下的Remote notifications权限
  2. 依赖用户点击通知唤醒应用,此时OneSignal会自动启动你的主页面
  3. 若需特殊场景的自动唤醒(如VoIP、定位更新),需申请对应系统权限,并在OneSignal控制台配置对应类型的推送

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:52:39