gpt4 book ai didi

android - FusedLocationApi.getLastLocation 返回 null

转载 作者:行者123 更新时间:2023-11-30 00:25:55 25 4
gpt4 key购买 nike

我有定位服务的单例

public class LocationService implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {

public static final String TAG = LocationService.class.getSimpleName();

private static LocationService instance;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
public Location location;
private Context context;

private LocationService (Context context) {

this.context = context;

mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

mGoogleApiClient.connect();

mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(60 * 1000); // 1 second, in milliseconds

}

public static LocationService getInstance(Context context){

if (null == instance){
instance = new LocationService(context);
}
return instance;
}

@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");

if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

this.location = location;

if (location != null) {
Log.d(TAG, location.toString());
}
}

@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}

public void onLocationChanged(Location location) {

this.location = location;

Log.i(TAG, "Location changed.");
Log.i(TAG, location.toString());

}
}

我通过调用 onCreateMainActivity 中启动它

LocationService locationService = LocationService.getInstance(getApplicationContext());

但我的位置始终为空并且 onLocationChanged 不会被调用

OnConnected 正在被调用,我检查了调试器,但是 location 里面是空的

我做错了什么?

最佳答案

如果您的最后一个位置为空,您需要至少注册一次以获取更新,以获取第一个最后位置。

Check the documentation 对于“请求位置更新”。

关于android - FusedLocationApi.getLastLocation 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com