android – 为什么FusedLocationApi.getLastLocation为null
作者:互联网
我试图通过使用FusedLocationApi.getLastLocation来获取位置,并且我在清单文件中获得了位置权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
但是,当我从系统请求位置时,我将变为null.我只是测试关闭和位置服务,所以它可能与此有关(当然,当我尝试这个时它是开启的).但即使在返回null之后,我也在等待onLocationChanged被调用,而且它永远不会被调用.我在这里也看到了类似的问题:FusedLocationApi.getLastLocation always null
这是我的代码:
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(30000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
return mLocationRequest;
}
protected GoogleApiClient getLocationApiClient(){
return new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
LocationRequest locationRequest = createLocationRequest();
@Override
public void onLocationChanged(Location location) {
App.setLocation(location); // NEVER CALLED
}
@Override
public void onConnected(Bundle bundle) {
App.setLocation(LocationServices.FusedLocationApi.getLastLocation(locationApiClient)); //RETURNS NULL
LocationRequest locationRequest = createLocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(locationApiClient, locationRequest, this);
}
在onCreate我的应用程序:
locationApiClient = getLocationApiClient();
locationApiClient.connect();
这是我的应用程序对象.
为什么我得到null(是的,我知道它可能在文档中所述的极少数情况下为空,但我总是得到这个,而不是很少)并且之后仍然没有得到位置更新?这是一个没有SIM卡的真实设备(三星Galaxy S3),如果有帮助的话.
解决方法:
我在我的应用程序中使用FusedLocationProvider api,
这是我的代码在设备和模拟器上都有效 –
@Override
protected void onCreate(Bundle savedInstanceState){
//put your code here
....
getLocation();
}
private void getLocation(){
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(LOCATION_INTERVAL);
locationRequest.setFastestInterval(LOCATION_INTERVAL);
fusedLocationProviderApi = LocationServices.FusedLocationApi;
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
public void onConnected(Bundle arg0) {
fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
Toast.makeText(mContext, "location :"+location.getLatitude()+" , "+location.getLongitude(), Toast.LENGTH_SHORT).show();
}
这是我的工作代码.
希望我的代码可以帮到你.
干杯..
标签:android,android-4-4-kitkat,android-location,fusedlocationproviderapi,android-fus 来源: https://codeday.me/bug/20190923/1815220.html