2

我正在为我的应用程序使用React 本机权限包。我想同时显示 Android 和 ios 的权限对话框。有了这个包,我可以看到我的 IphoneSimulator's权限对话框,但我看不到任何东西是 Android Emulator。我不明白我在犯什么错误。

这是我为 Android 设置的:

文件:android/app/main/AndroidManifest.xml

我添加了这一行

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.locationApp">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />   
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />   

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <meta-data
         android:name="com.google.android.geo.API_KEY" 
         android:value="API_KEY"/> 
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

在 Build gradle: > file: android/build.gradle 我添加这个:

ext {
   ....
    playServicesVersion = "17.0.0" 
    androidMapsUtilsVersion = "2.2.0" 
}

这是我的代码:

import React, { useEffect, useState } from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Platform,
  View,
} from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import Geolocation from 'react-native-geolocation-service';

const Permission = () => {
  const [location, setLocation] = useState({
    latitude: 60.1098678,
    longitude: 24.7385084,
  });

  const handleLocationPermission = async () => {
    let permissionCheck = '';
    if (Platform.OS === 'ios') {
      permissionCheck = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);

      if (permissionCheck === RESULTS.DENIED) {
        const permissionRequest = await request(
          PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
        );
        permissionRequest === RESULTS.GRANTED
          ? console.warn('Location permission granted.')
          : console.warn('Location perrmission denied.');
      }
    }

    if (Platform.OS === 'android') {
      permissionCheck = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);

      if (permissionCheck === RESULTS.DENIED) {
        const permissionRequest = await request(
          PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
        );
        permissionRequest === RESULTS.GRANTED
          ? console.warn('Location permission granted.')
          : console.warn('Location perrmission denied.');
      }
    }
  };

  useEffect(() => {
    handleLocationPermission();
  }, []);

  useEffect(() => {
    Geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        setLocation({ latitude, longitude });
      },
      (error) => {
        console.log(error.code, error.message);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
    );
  }, []);

  return (
    <View style={styles.container}>
      <MapView
        style={styles.map}
        provider={PROVIDER_GOOGLE}
        initialRegion={{
          latitude: location.latitude,
          longitude: location.longitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
         showsUserLocation={true}
          paddingAdjustmentBehavior={'automatic'}
          showsMyLocationButton={true}
          showsBuildings={true}
          maxZoomLevel={17.5}
          loadingEnabled={true}
          loadingIndicatorColor={'#fcb103'}
          loadingBackgroundColor={'#242f3e'}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

export default Permission;
4

1 回答 1

0

您好,您只能通过以下代码为 ios 和 android 使用功能

 let permission = PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION;
      if (Platform.OS === 'android') AskPermission(permission);
      if (Platform.OS === 'ios') {
        Geolocation.requestAuthorization('whenInUse');
      }

这是AskPermission函数

import {PermissionsAndroid} from 'react-native';

 const AskPermission = async (permission) => {
  try {
    const granted = await PermissionsAndroid.request(permission, {
      title: 'Location Permission',
      message: 'Allow Location Permission.',
      //   buttonNeutral: "Ask Me Later",
      //   buttonNegative: "Cancel",
      buttonPositive: 'OK',
    });
    if (granted === true || granted === PermissionsAndroid.RESULTS.GRANTED) {
      // console.warn("Permission Granted");
    } else {
      // console.warn("Permission Denied");
    }
  } catch (err) {
    console.warn(err);
  }
};
于 2021-09-16T06:21:31.673 回答