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

Android 12(API 31)下Xamarin.Forms的BroadcastReceiver无法触发问题

解决Android 12(API 31)下GeofenceReceiver不触发的问题

核心问题分析

Android 12(API 31)收紧了隐式广播的静态注册限制,同时针对地理围栏(Geofence)的广播触发新增了更严格的校验规则。你的接收器当前仅注册了Intent.ActionBootCompleted动作,未配置地理围栏相关的Intent过滤,且静态注册方式在Android 12下对部分隐式广播不再生效。

具体修复步骤

1. 补充地理围栏相关的IntentFilter配置

GeofenceReceiver需要监听地理围栏触发的动作,必须在IntentFilter中添加GeofencingManager.ActionGeofenceTransition,调整后的代码如下:

[BroadcastReceiver(Exported = true, Enabled = true)]
[IntentFilter(new[] { 
    Intent.ActionBootCompleted,
    GeofencingManager.ActionGeofenceTransition 
})]
public class GeofenceReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == GeofencingManager.ActionGeofenceTransition)
        {
            // 解析地理围栏触发类型(进入/离开)
            int transitionType = intent.GetIntExtra(GeofencingManager.ExtraGeofenceTransition, -1);
            if (transitionType == Geofence.GeofenceTransitionEnter || transitionType == Geofence.GeofenceTransitionExit)
            {
                // 执行你的业务逻辑
            }
        }
        else if (intent.Action == Intent.ActionBootCompleted)
        {
            // 开机后重新注册地理围栏的逻辑
        }
    }
}

2. 适配Android 12的显式Intent要求

Android 12及以上,隐式广播的静态接收器无法被系统触发,注册地理围栏时需使用显式Intent指定接收器:

// 创建地理围栏触发时的Intent
var intent = new Intent(Application.Context, typeof(GeofenceReceiver));
intent.SetAction(GeofencingManager.ActionGeofenceTransition);

// 创建PendingIntent,Android 12及以上需添加Mutable标记
var pendingIntent = PendingIntent.GetBroadcast(
    Application.Context,
    0,
    intent,
    PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Mutable
);

// 注册地理围栏
var geofencingClient = LocationServices.GetGeofencingClient(Application.Context);
await geofencingClient.AddGeofencesAsync(geofencingRequest, pendingIntent);

3. 确认清单权限配置

确保AndroidManifest.xml中已正确声明所需权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

4. 规避后台进程回收

Android 12对后台应用限制严格,若业务需要持续监听地理围栏,可添加前台服务保持进程存活,避免被系统优化回收。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:10:19