我有一个向用户发出位置请求的代码,只要用户已经处于“位置”模式,则一切正常,但是,如果未在设备通知栏位置激活“位置”模式,返回null,我知道当我们禁用该选项时,会清除位置缓存,如何要求用户激活q的选项,然后再请求getLastLocation?
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
localidade = task.getResult();
if(localidade != null){
try {
locFromLatLon = new Geocoder(AddAnuncioActivity.this, Locale.getDefault());
List<Address> addresses = locFromLatLon.getFromLocation(localidade.getLatitude(), localidade.getLongitude(), 1);
Log.i("VALORZAS", addresses.get(0).getCountryName());
} catch (IOException e) {
e.printStackTrace();
}
}else{
// Put some here whenlocation is null -- this happens when the Location option in notification bar of // user is unabled
}
}
});
仅当启用了图像中的选项时,此选项才起作用;如果禁用此选项,则getResult返回null。
我的onResume函数:
@Override
protected void onResume() {
super.onResume();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(60000);
locationRequest.setFastestInterval(5000);
LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Toast.makeText(getApplicationContext(), "Localidade ainda vazia", Toast.LENGTH_LONG).show();
return;
}
for (Location location : locationResult.getLocations()) {
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
您可以尝试使用LocationManager
: