gpt4 book ai didi

android - getLastKnownLocation 在 Android 中返回 null

转载 作者:太空狗 更新时间:2023-10-29 13:25:05 25 4
gpt4 key购买 nike

我知道这已被讨论过很多次,但没有任何帮助我解决 getLastKnownLocation 返回 null 的问题。

我的 Activity 实现 LocationListener:

public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

我的 onCreate 方法中有这个:

  LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

然后我尝试像这样获取用户位置(也在 onCreate 中):

    // Getting the Co-ordinates of the users current location
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if(location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}

我试过:

@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}

我错过了什么吗?

编辑:仍然无法正常工作,但我已经尝试过的代码:

    if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
while (location == null) {
if (counter > MAX_TIME) {
}
else {
try {
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter += 1000;
}
}
}

最佳答案

来自文档:

“返回一个位置,该位置指示从给定提供商处获得的最后一个已知位置定位的数据。

返回提供者的最后已知位置,或 null"

因此,必须至少有一个使用提供的提供程序获得的先前位置。要接收位置,您必须使用该提供商至少注册一次更新并接收实际更新。之后,getLastKnownLocation 将返回该值。如果您想注册其他应用提供的位置,请使用 Location.PASSIVE_PROVIDER。

希望这对您有所帮助。

编辑:正如我在上面评论的那样,在其中放置一个 while 循环,迭代 30 秒并每秒检查一次位置是否不再为空。您需要至少发生一次,然后才能使用 getLastKnownLocation,AFAIK。

使用未经测试的小示例进行编辑。最好也将所有这些都放在 AsyncTask 中,即在 doInBackground 中。请注意,我假设您正在存储 Location 对象本身,而不是将其分离为经度和纬度。:

if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
long final MAX_TIME = 30000;
long counter = 0;
while (location == null) {
if (counter > MAX_TIME) {
return False;
}
Thread.sleep(1000);
counter += 1000;
}
} else {
return False;
}

编辑:请记住,位置在 onLocationUpdate(Location location) 中更新。其中一个已更新,然后您有一个不等于 null 的位置对象。

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

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