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

React Native使用Geolocation时应用崩溃求助

问题分析与修复方案

你的代码存在几个关键问题,正是这些问题导致了授权后应用闪退:

1. 权限请求逻辑错误

你混用了react-native-permissions和原生PermissionsAndroid的API,且请求权限后未更新权限状态。初始的granted变量始终是请求前的状态,不会触发后续的位置获取逻辑,反而容易引发逻辑异常。

2. 权限弹窗参数不合法

你设置了buttonPositive: ''空字符串,这会导致Android权限弹窗的确认按钮无法正常渲染,直接引发界面崩溃。

3. Android 12+权限适配缺失

如果项目的targetSdkVersion >=31(对应Android 12及以上),仅声明ACCESS_FINE_LOCATION权限不够,还需要补充ACCESS_COARSE_LOCATION权限,否则权限请求流程会出现异常。


修复后的完整代码

import { check, request, RESULTS, PERMISSIONS } from 'react-native-permissions';
import Geolocation from 'react-native-geolocation-service';
import { Alert } from 'react-native';
import { Dispatch } from 'redux';

export const getCity = async (dispatch: Dispatch<any>) => {
  let granted = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);

  if (granted === RESULTS.DENIED) {
    // 使用react-native-permissions统一的request方法
    const requestResult = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION, {
      title: '位置权限请求',
      message: '应用需要获取您的位置信息来获取城市数据,请授予权限',
      buttonPositive: '允许',
      buttonNegative: '取消',
    });
    // 更新权限状态
    granted = requestResult;
  }

  if (granted === RESULTS.GRANTED || granted === RESULTS.LIMITED) {
    try {
      // 改用async/await形式处理位置获取,避免回调嵌套的异常
      const position = await Geolocation.getCurrentPosition({
        enableHighAccuracy: false,
        timeout: 20000,
        maximumAge: 3600000,
      });
      const coords = {
        Longitude: position.coords.longitude,
        Latitude: position.coords.latitude,
      };
      dispatch(thunks.geocoder.getGeocoderInfo(coords));
      Alert.alert('坐标信息', `${coords.Latitude}, ${coords.Longitude}`);
    } catch (error: any) {
      Alert.alert('获取位置失败', `错误信息:${error.message}`);
    }
  } else {
    Alert.alert('权限未授予', '无法获取位置信息,请在设置中开启位置权限');
  }
};

额外配置与检查

  • 补充AndroidManifest.xml权限:如果targetSdkVersion >=31,添加以下权限声明:
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
  • 依赖版本检查:确保react-native-geolocation-service和react-native-permissions为最新稳定版,避免版本兼容问题。
  • 位置服务状态校验:可以在获取位置前添加设备位置服务状态检查,避免因服务未开启导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:06:23