You need to enable JavaScript to run this app. Expo应用如何在后台或关闭时运行geofencing并按推送经纬度判断展示通知
优惠活动
大模型
产品
解决方案
定价
更多

Expo应用如何在后台或关闭时运行geofencing并按推送经纬度判断展示通知

后台地理围栏实现完整方案

核心实现思路

不要采用持续后台定位做实时比对的方案,这类方案耗电量高、极易被系统杀死,无法支撑应用完全关闭状态下的运行要求。Expo提供系统级地理围栏能力,监控逻辑由系统底层承担,不需要应用持续持有定位进程,触发时才会唤起轻量后台上下文执行逻辑,完全匹配需求。

第一步:全局注册系统级地理围栏任务

这部分代码必须放在所有React组件定义之前,不能写在组件生命周期内——应用完全关闭时组件树不会挂载,只有全局注册的任务才能被系统唤起执行。

// 放在文件最顶层,import语句之后、App组件定义之前
import AsyncStorage from '@react-native-async-storage/async-storage';

const GEOFENCE_TASK = 'geofence-region-alert';
const STORED_GEOFENCE_KEY = 'persisted_geofence_list';

// 全局注册后台地理围栏任务,和系统位置服务绑定,应用关闭也能被唤起
TaskManager.defineTask(GEOFENCE_TASK, async ({ data: { eventType, region }, error }) => {
  if (error) {
    console.error('地理围栏任务异常', error);
    return;
  }
  // 仅当设备进入围栏范围时触发逻辑
  if (eventType === Location.GeofencingEventType.Enter) {
    // 从本地持久化存储读取对应的围栏描述信息
    const storedList = JSON.parse(await AsyncStorage.getItem(STORED_GEOFENCE_KEY) || '[]');
    const matchedRegion = storedList.find(
      item => item.lat === region.latitude && item.lon === region.longitude
    );
    if (matchedRegion) {
      // 直接弹出系统通知,不需要打开应用前台
      await Notifications.presentNotificationAsync({
        title: '区域提醒',
        body: matchedRegion.description,
        data: matchedRegion
      });
    }
  }
});

第二步:封装通用处理工具函数

针对你服务端约定的[<$>]分隔格式,实现参数解析、围栏注册的通用逻辑,覆盖全场景处理需求:

// 解析推送携带的地理围栏参数
function parsePushParams(pushContent) {
  const paramList = pushContent.split('[<$>]');
  return {
    description: paramList[0],
    lat: Number(paramList[1]),
    lon: Number(paramList[2]),
    radius: Number(paramList[3])
  };
}

// 把解析出的参数注册为系统级地理围栏,并持久化存储
async function registerSystemGeofence(geofenceParam) {
  // 同步更新本地存储的围栏参数列表
  const storedList = JSON.parse(await AsyncStorage.getItem(STORED_GEOFENCE_KEY) || '[]');
  const existIndex = storedList.findIndex(
    item => item.lat === geofenceParam.lat && item.lon === geofenceParam.lon
  );
  if (existIndex >= 0) {
    storedList[existIndex] = geofenceParam;
  } else {
    storedList.push(geofenceParam);
  }
  await AsyncStorage.setItem(STORED_GEOFENCE_KEY, JSON.stringify(storedList));

  // 向系统注册地理围栏监控
  await Location.startGeofencingAsync(GEOFENCE_TASK, [{
    latitude: geofenceParam.lat,
    longitude: geofenceParam.lon,
    radius: geofenceParam.radius,
    notifyOnEnter: true,
    notifyOnExit: false
  }]);
}

第三步:重构通知全链路处理逻辑

替换原有代码里的通知监听逻辑,覆盖前台、后台、应用完全关闭三种状态下的推送接收处理:

async componentDidMount() {
  console.log('App mounted');
  // 1. 前台运行时收到推送的处理
  this._notificationSubscription = Notifications.addListener(async (notification) => {
    this.setState({ notification });
    // 从推送的自定义data字段读取围栏参数
    const pushParam = notification.data?.pushBody;
    if (pushParam) {
      const geofenceParam = parsePushParams(pushParam);
      await registerSystemGeofence(geofenceParam);
    }
  });

  // 2. 应用完全关闭时被推送唤起的场景:读取启动时携带的通知参数
  const launchNotification = await Notifications.getLastNotificationResponseAsync();
  const launchPushParam = launchNotification?.notification?.request?.content?.data?.pushBody;
  if (launchPushParam) {
    const geofenceParam = parsePushParams(launchPushParam);
    await registerSystemGeofence(geofenceParam);
  }

  // 3. 应用在后台/被系统挂起时收到推送的场景:注册后台推送处理任务
  TaskManager.defineTask('push-background-handler', async ({ data, error }) => {
    if (error) return;
    const backgroundPushParam = data?.notification?.data?.pushBody;
    if (backgroundPushParam) {
      const geofenceParam = parsePushParams(backgroundPushParam);
      await registerSystemGeofence(geofenceParam);
    }
  });
  // 给通知模块绑定后台任务
  Notifications.registerTaskAsync('push-background-handler');
}

落地注意事项

  • 服务端推送时,要把拼接好的PushBody整个放到推送的data.pushBody自定义字段里,不要直接当通知body发送——否则收到推送的瞬间就会弹出系统通知,不符合“进入围栏范围才弹通知”的需求
  • 系统级地理围栏的监控逻辑由系统位置服务承担,不需要APP一直持有定位进程,哪怕被用户手动杀掉,只要位置权限未被关闭,系统依然会持续监控围栏状态
  • 围栏对应的描述参数必须存在AsyncStorage这类持久化存储里,不要存在组件state中——应用关闭时组件state会被完全清空,系统唤起后台任务时无法读取内存里的参数
  • 同一个坐标的围栏重复注册时,系统会自动去重,不会重复触发任务,不需要额外做删除旧围栏的兼容处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 04:54:02