我正在为我的 Android React Native 应用程序请求位置权限。我正在使用 npm 包:react-native-permissions
. 我创建了一个自定义挂钩来执行此操作。
我的 iOS 实现完美。在 Android 上尝试类似方法时,从未弹出询问用户位置许可的对话框。在我最初检查权限时,我的应用报告权限已被授予!!但是怎么做?
我将它包含在我的 AndroidManifest.xml 中:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
这是我请求许可的钩子:
export default (setPermissionsGranted = () => {}, setPermissionError = () => {}) => {
const appState = useRef(AppState.currentState)
const [shouldCheckPermission, setShoudCheckPermission] = useState(false)
useEffect(() => {
let isMounted = true
const handleAppState = (nextAppState) => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
// the app has come into the foreground. Change a boolean state variable to trigger
// handlePermission() again.
if (isMounted) setShoudCheckPermission(!shouldCheckPermission)
}
appState.current = nextAppState
}
const handlePermissionStatus = (result) => {
const status = {
unavailable: () => {},
denied: async () => {
const res = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
if (isMounted) {
if (res === RESULTS.GRANTED) {
setPermissionsGranted(true)
} else {
setPermissionsGranted(false)
}
}
},
limited: () => {
// todo find out what limited entails
if (isMounted) setPermissionsGranted(true)
},
granted: async () => {
if (isMounted) setPermissionsGranted(true)
},
blocked: () => {
if (isMounted) setPermissionsGranted(false)
},
}
return status[result]
}
AppState.addEventListener('change', handleAppState)
const handlePermission = async () => {
console.log('permissions code is run')
try {
const res = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
console.log('res', res)
handlePermissionStatus(res)()
} catch (err) {
throw err
}
}
handlePermission().catch((e) => {
if (isMounted) setPermissionError(e.message)
})
return () => {
AppState.removeEventListener('change', handleAppState)
isMounted = false
}
}, [shouldCheckPermission])
}
关于为什么用户永远不会被询问并且权限被自动授予的任何解释?
另一个特点是,我已经注释掉了所有在 Android 上请求位置权限的代码,重新启动了 Metro 服务器,卸载了该应用程序,然后重新安装了它。request-permissions 标记仍在 AndroidManifest.xml 中。显然这就是我需要做的所有事情,现在权限已自动授予!
我的理解是,这是一个危险的权限,不应自动授予,但 Android 将其视为安全权限。♂️</p>
提前致谢。