如果您还想在后台访问用户的位置,请在访问后台位置之前使用该API,并在清单文件中添加后台权限:enableBackgroundMode({bool enable})
对于 iOS
将以下位置权限添加到:Info.plist
NSLocationWhenInUseUsageDescription
此应用需要访问您的位置
NSLocationWhenInUseUsageDescription
是您需要的唯一许可。这也允许您访问后台位置,唯一需要注意的是,当应用程序在后台访问位置时,状态栏中会显示蓝色徽章。与 Android 不同,我们在其中添加了单独的权限以在后台访问用户的位置。
位置权限
我们需要在请求用户位置之前检查位置服务状态和权限状态,这可以使用以下几行代码轻松完成:
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return null;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return null;
}
}
首先,我们创建一个由Location()
包提供的对象,location反过来为我们提供了两个有用的方法。检查设备位置是否已启用或用户是否已手动禁用它。``serviceEnabled()
对于后者,我们显示了一个原生提示,允许用户通过调用快速启用位置,然后我们再检查一次,如果他们从提示中启用了它。requestService()
一旦我们确定启用了位置服务,下一步就是通过调用它来检查我们的应用程序是否具有使用它的必要权限,这将返回.hasPermission()``PermissionStatus
PermissionStatus
是可以具有以下三个值之一的枚举: