gpt4 book ai didi

java - LocationServices.FusedLocationApi.requestLocationUpdates 未设置位置

转载 作者:行者123 更新时间:2023-11-29 20:52:51 25 4
gpt4 key购买 nike

我正在尝试使用 GoogleAPIClient 获取实时位置更新。虽然 GoogleAPIClient 已连接但位置对象为空,并且它提示 location.getProvider() 为空。有人可以帮忙吗?

这是我的代码:

public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient " + myGoogleApiClient.isConnected());

myCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(myGoogleApiClient);
// Debug - At this point myCurrentLocation is NULL
if (myCurrentLocation == null) {
Log.i(TAG, "myCurrentLocation is : " + myCurrentLocation);
// Debug - myCurrentLocation is STILL NULL
LocationServices.FusedLocationApi.requestLocationUpdates(
myGoogleApiClient, myLocationRequest, this);
// Debug - app crashes with stack trace below at this point
Log.i(TAG, "Doesnt't reach here : " + myCurrentLocation);
}

myLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUILayout();

}

protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
myGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Log.i(TAG, "myGoogleApiClient is :" + myGoogleApiClient.isConnected());
createLocationRequest();
}

protected void createLocationRequest() {
myLocationRequest = new LocationRequest();
myLocationRequest.setInterval(10000);
myLocationRequest.setFastestInterval(5000);
myLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

调试后我发现的主要问题是:

 LocationServices.FusedLocationApi.requestLocationUpdates(
myGoogleApiClient, myLocationRequest, this);

这不是设置 myCurrentLocation。它始终为 NULL。在 ADB logcat 中说:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.location.Location.getProvider()' on a null object reference
at com.adrenalin.myfirstapp.MyActivity.onConnected(MyActivity.java:130)
at com.google.android.gms.internal.jm.f(Unknown Source)
at com.google.android.gms.common.api.c.gJ(Unknown Source)
at com.google.android.gms.common.api.c.d(Unknown Source)
at com.google.android.gms.common.api.c$2.onConnected(Unknown Source)
at com.google.android.gms.internal.jm.f(Unknown Source)
at com.google.android.gms.internal.jm.dU(Unknown Source)
at com.google.android.gms.internal.jl$h.b(Unknown Source)

最佳答案

当你实现

LocationServices.FusedLocationApi.requestLocationUpdates(
myGoogleApiClient, myLocationRequest, this);

您需要覆盖 onLocationChanged 的回调,以便它知道在更新时如何处理位置。

试试这个:

@Override
public void onLocationChanged(Location location) {
myCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

关于java - LocationServices.FusedLocationApi.requestLocationUpdates 未设置位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648690/

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