我使用网络代码获取gps位置:
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
所有工作都很好,除非我的设备已停用位置服务getFusedLocationProviderClient打开一个对话框并告诉该设备需要wifi,手机网络和传感器。我同意和应用程序激活我的位置服务,但功耗设置较低(省电模式)。
我做错了什么?看起来GPS传感器未激活,因为我的位置远离我的真实位置。如果我做手动,设置都像魅力一样。
答案 0 :(得分:1)
解决了我的问题!
Task<LocationSettingsResponse> result;
............
getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
这也激活了GPS:
result = LocationServices.getSettingsClient(this).checkLocationSettings(locationSettingsRequest);
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvable = (ResolvableApiException) exception;
resolvable.startResolutionForResult(
NewMainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//
} catch (ClassCastException e) {
//
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
答案 1 :(得分:0)
我建议改变优先顺序。低电池系统的优先级不应该高。 你在Android Oreo上运行吗?然后,此功能必须在作业调度程序下。 In Oreo (8.0.0+) (API 26+), How to get a location services update when the app is in the background or kill