【发布时间】:2021-10-20 16:20:44
【问题描述】:
目前受影响的设备:
- Xperia 1 II
- 小米红米 Note 7
用途: 为了请求位置更新,我检查了位置设置 事先就足够了。如果没有,我显示一个小文本,服务必须 为我的功能启用。如果用户点击它,系统对话框启用 会提示定位服务。
我如何运行检查:
我通过LocationSettingsRequest 和LocationServices 运行检查和
处理ResolvableApiException。如果该服务被用户禁用,
然后在我所有的设备上,这将显示系统对话框,要求用户启用
服务(并启用它,如果单击确定)。
在 Redmi 上会发生什么:
但无论出于何种原因,在小米红米 Note 7 上,checkLocationSettings
将总是返回 ResolvableApiException,即使服务
已启用。对话框不会出现并直接返回肯定结果
(当然,因为该服务已启用)。
因此,用户被卡住并永远点击“启用”。
有人知道为什么LocationSettingsRequest 不工作吗
在这些设备上正常运行并且知道如何修复它?
示例代码 sn-p
void enableLocationSettings(onLocationServiceRequiredCallback: ICallback) {
LocationRequest locationRequest = LocationRequest.create()
.setInterval(LOCATION_UPDATE_INTERVAL)
.setExpirationDuration(LOCATION_UPDATE_EXPIRATION_DURATION)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationServices
.getSettingsClient(this)
.checkLocationSettings(builder.build())
.addOnSuccessListener(this, (LocationSettingsResponse response) -> {
// update location as usual
})
.addOnFailureListener(this, error -> {
if (error instanceOf ApiException) {
int statusCode = error.statusCode;
if(statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
if(error instanceOf ResolvableApiException) {
PendingIntent resolution = error.resolution
// This will trigger the system dialog, see below
onLocationServiceRequiredCallback(resolution);
}
}
}
// error callback
});
不幸的是,回调的代码现在将是 kotlin。对此感到抱歉。我只能发布“示例代码 sn-ps”,因为这是与工作相关的。
它使用ActivityResultContracts.StartIntentSenderForResult 启动
系统对话框。
resolution 是上面的 PendingIntent。
合同:
private val locationServiceContract = registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult()
) { activityResult ->
lifecycleScope.launchWhenResumed {
val result = if (activityResult.resultCode == Activity.RESULT_OK) {
// This will retrigger the location fetch (looping)
enableLocationSettings(...)
} else {
// Do nothing
}
}
}
调用上面的回调后,这将被执行:
locationServiceContract.launch(
IntentSenderRequest.Builder(
resolution
).build()
)
LocationSettingsStates 的转储,使用已弃用的 LocationSettings API(使用 GoogleApiClient)获取:
isGpsPresent: true,
isGpsUsable: false,
isLocationPresent: true,
isLocationUsable: true,
isNetworkLocationPresent: true,
isNetworkLocationUsable: true
【问题讨论】:
标签: android location google-play-services