问题
I am currently working on an app using react native that requires location services to be on for some of its features. I have been researching if there is a simple way to test if the user has them turned on or not so I can display a different view if they aren't. I have not found any results other than ones that are specific to IOS or Android. Has anyone else found a solution to this?
回答1:
Use the "react native android location services dialog box" module for android
https://www.npmjs.com/package/react-native-android-location-services-dialog-box
install
npm install react-native-android-location-services-dialog-box --save
js
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";
LocationServicesDialogBox.checkLocationServicesIsEnabled({
message: "Use Location ?",
ok: "YES",
cancel: "NO"
}).then(function(success) {
console.log(success); // success => "enabled"
).catch((error) => {
console.log(error.message); // error.message => "disabled"
});
回答2:
I was able to solve this by displaying an error message when the location could not be retrieved.
(error) => {
this.setState({servicesOn: false}),
console.log(error);
},
回答3:
Do a watchPosition or getCurrentPosition, Your second argument is a callback in case of failure, and its argument is the reason it failed.
So, from there you know when and why it fails. You'll need an if for the reason if you only want to act on 'location disabled' and not 'request timed out' for example.
You can use the callback to add a flag to your state for example.
回答4:
You can also try out these 2 libraries:
https://github.com/c19354837/react-native-system-setting
https://github.com/efkan/react-native-system-settings
What I have is the following: I get this error code 1 or error message: 'No location provider available.' when my phone location service is turned off.
Other time, when it times out, I get this error code 3 or error message: 'Location request timed out.'.
Thus, based on the error code and message, I display different toasts to inform the user.
You can refer to this position error doc on MDN
来源:https://stackoverflow.com/questions/36776780/checking-if-location-services-are-enabled-using-react-native