gpt4 book ai didi

android - getLastKnownLocation 返回 NULL

转载 作者:IT老高 更新时间:2023-10-28 23:39:10 28 4
gpt4 key购买 nike

我刚刚开始工作,但是当我关闭 Wifi 以查看是否可以使用 GPS 获得更准确的位置时,它现在给我带来 NullPointer 错误,我看不到为什么。

下面的代码首先被调用;

 public void onConnected(Bundle dataBundle) {
connected = true;
//Request an update from the location client to get current Location details
mLocationClient.requestLocationUpdates(mLocationRequest,this);
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}

然后需要调用此方法

public void onLocationChanged(android.location.Location location) {
// Report to the UI that the location was updated
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
if(tmp != location.getLatitude())
{
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
tmp = location.getLatitude();
}

您可以看到我在那里有 2 个 toast ,它们返回的实际 GPS 坐标很好,但是当我调用下面的代码时,它会在新的位置行 getLastKnownLocation

上崩溃
public String getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show();
return new LatLng(lat, lon).toString();
}
catch (NullPointerException e){
Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show();
Log.e("HELL-NO","n",e);
e.printStackTrace();
return null;
}
}

我只是不明白为什么当我尝试检索似乎已在 onLocationChanged 方法中检索到的位置时,它只是提供了一个空指针。

最佳答案

我只是改变了

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) to 
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

这为我解决了解决方案。完整 fragment :

map  = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();

map.setMyLocationEnabled(true);

locationManager = (LocationManager)getSystemService
(Context.LOCATION_SERVICE);
getLastLocation = locationManager.getLastKnownLocation
(LocationManager.PASSIVE_PROVIDER);
currentLongitude = getLastLocation.getLongitude();
currentLatitude = getLastLocation.getLatitude();

currentLocation = new LatLng(currentLatitude, currentLongitude);

希望这会有所帮助。

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

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