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

Expo-Location在Android APK中无法获取设备当前位置的问题

Expo Location在Android APK中无法获取位置(Expo Go/iOS正常)

问题描述

已授予位置权限,但通过Expo构建的Android APK无法获取设备位置,而Expo Go和iOS应用中代码可正常运行,无明确错误提示。

核心代码:

import * as Location from "expo-location";
// ...

React.useEffect(() => {
    (async () => {
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Permission to access location was denied');
            return;
        }
        let location = await Location.getCurrentPositionAsync({});
        setUserLatitude(location?.coords?.latitude);
        setUserLongitude(location?.coords?.longitude);
    })();
}, []);

环境信息:

  • Expo SDK版本:49.0.6
  • React Native版本:0.72.6
  • expo-location版本:16.1.0

解决方案

1. 确认权限配置

检查app.json/app.config.js中的Android权限声明,确保包含必要的定位权限:

{
  "expo": {
    "android": {
      "permissions": [
        "ACCESS_COARSE_LOCATION",
        "ACCESS_FINE_LOCATION"
        // 若需后台定位,添加 "ACCESS_BACKGROUND_LOCATION"
      ]
    }
  }
}

Expo构建APK时会将这些权限合并到AndroidManifest.xml中,缺失权限可能导致定位失败。

2. 检查位置服务状态

Android设备可能关闭了位置服务,即使权限已授予也无法获取位置。在获取位置前添加服务检查:

import * as Location from "expo-location";

React.useEffect(() => {
    (async () => {
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Permission to access location was denied');
            return;
        }

        // 检查位置服务是否开启
        const isLocationEnabled = await Location.hasServicesEnabledAsync();
        if (!isLocationEnabled) {
            console.log('Location services are disabled');
            // 可在此提示用户打开位置服务
            return;
        }

        // 配置定位参数(提高精度、设置超时)
        try {
            let location = await Location.getCurrentPositionAsync({
                accuracy: Location.Accuracy.High,
                timeout: 10000,
                maximumAge: 0
            });
            setUserLatitude(location?.coords?.latitude);
            setUserLongitude(location?.coords?.longitude);
        } catch (error) {
            console.error('Failed to get location:', error);
        }
    })();
}, []);

3. 检查构建混淆规则

如果自定义了ProGuard规则,确保Expo Location相关类未被混淆,添加以下规则到proguard-rules.pro:

-keep class expo.modules.location.** { *; }

4. 验证设备定位设置

部分Android设备需要将定位模式设置为高精度(GPS+网络),仅GPS模式在室内可能无法获取位置。引导用户检查设备的定位模式设置。

5. 捕获定位错误

添加try-catch捕获getCurrentPositionAsync的错误,可获取具体失败原因(如超时、信号弱等),便于排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:42:40