【发布时间】:2018-12-08 09:28:11
【问题描述】:
有没有办法在 Flutter 中查明 GPS 是激活还是停用? 我使用插件location 但是我只得到位置而不是 GPS 的状态。
【问题讨论】:
有没有办法在 Flutter 中查明 GPS 是激活还是停用? 我使用插件location 但是我只得到位置而不是 GPS 的状态。
【问题讨论】:
bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
以前的解决方案:
接受的答案使用过时的插件,你可以使用Geolocator插件,
var geoLocator = Geolocator();
var status = await geoLocator.checkGeolocationPermissionStatus();
if (status == GeolocationStatus.denied)
// Take user to permission settings
else if (status == GeolocationStatus.disabled)
// Take user to location page
else if (status == GeolocationStatus.restricted)
// Restricted
else if (status == GeolocationStatus.unknown)
// Unknown
else if (status == GeolocationStatus.granted)
// Permission granted and location enabled
【讨论】:
使用最新版本的Geolocator 5.0
var isGpsEnabled = await Geolocator().isLocationServiceEnabled();
如果禁用,我使用此方法检查并启用 Gps。
Future _checkGps() async {
if (!(await Geolocator().isLocationServiceEnabled())) {
if (Theme.of(context).platform == TargetPlatform.android) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Can't get gurrent location"),
content:
const Text('Please make sure you enable GPS and try again'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
final AndroidIntent intent = AndroidIntent(
action: 'android.settings.LOCATION_SOURCE_SETTINGS');
intent.launch();
Navigator.of(context, rootNavigator: true).pop();
},
),
],
);
},
);
}
}
}
【讨论】:
2019 年 10 月 25 日更新
位置包现在有一个函数 (serviceEnabled()) 来检测位置服务是否已启用并返回一个布尔值,如其docs 中所述和example 中所示:
bool serviceStatus = await _locationService.serviceEnabled();
if (service) {
// service enabled
} else {
// service not enabled, restricted or permission denied
}
旧答案(包已过时)
使用geolocations,您可以检查定位服务是否正常运行。它通常比位置包包含更多的可定制性。
final GeolocationResult result = await Geolocation.isLocationOperational();
if(result.isSuccessful) {
// location service is enabled, and location permission is granted
} else {
// location service is not enabled, restricted, or location permission is denied
}
【讨论】:
checkLocationPermission() async {
final status = await Permission.location.request();
if (status == PermissionStatus.granted) {
debugPrint('Permission granted');
bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
if (isLocationEnabled) {
// location service is enabled,
} else {
// open Location settings
await Geolocator.openLocationSettings();
}
} else if (status == PermissionStatus.denied) {
debugPrint(
'Permission denied. Show a dialog and again ask for the permission');
} else if (status == PermissionStatus.permanentlyDenied) {
debugPrint('Take the user to the settings page.');
await openAppSettings();
}
}
【讨论】: