【发布时间】:2024-01-13 01:26:01
【问题描述】:
我正在开发 React 本机项目,并且正在获取位置权限。此外,我必须始终跟踪位置权限,例如用户是否在安装应用程序后授予权限访问权限,然后一段时间后用户转到设备设置中的应用程序设置并禁用/撤销权限。再次,一旦应用程序从后台到前台,我必须基于此检查权限,需要显示消息。
所以,我正在使用 Appstate。但是,奇怪的是,在 Android 中,安装应用程序后,如果用户使用“不再显示”复选框拒绝了该权限,那么 Appstate 会一直以 background 和 active 不断变化。 它一直在循环。
componentDidMount = async () => {
AppState.addEventListener('change', this.handleAppStateChange);
};
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
Geolocation.clearWatch(this.watchID);
}
handleAppStateChange = async nextAppState => {
const {appState} = this.state;
console.log('nextAppState -->', nextAppState);
console.log('appState -->', appState);
if (appState === 'active') {
// do this
this.showLoader();
await this.requestAndroidLocationPermission();
} else if (appState === 'background') {
// do that
} else if (appState === 'inactive') {
// do that other thing
}
this.setState({appState: nextAppState});
};
requestAndroidLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.getLatitudeLongitude();
} else if (granted === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
this.hideLoader();
this.setState({
errorMessage: 'Location permission is denied',
isLoading: false,
});
} else {
this.hideLoader();
this.requestAndroidLocationPermission();
}
} catch (err) {
console.warn(err);
}
};
在以不再显示的方式拒绝许可后继续打印(循环)
appState --> active
nextAppState --> background
appState --> active
nextAppState --> background
appState --> active
nextAppState --> background
appState --> active
它继续,永不停止。
如何处理?有什么建议吗?
【问题讨论】:
-
你使用的是什么版本的 React Native?最新的文档说明如下。 [facebook.github.io/react-native/docs/appstate#change] "通过监听更改事件类型并提供处理程序 TODO 为 AppState 更改添加处理程序:既然 AppState 是 NativeEventEmitter 的子类,我们可以弃用 addEventListener 和 removeEventListener 并直接使用 addListener 和 listener.remove()。不过,这将是一个重大变化,因为方法和事件名称都不同(当前要求 addListener 事件是全局唯一的)。"
-
你好,你的问题解决了吗,我也遇到同样的问题,不知道是什么问题!!!
-
@Yasir,不是我没有解决
-
我遇到了同样的问题,有人解决了吗?
标签: android react-native geolocation location addeventlistener