我剛剛得到這個工作,但當我關閉我的Wifi,看看我是否可以使用我的GPS獲得更準確的位置,它現在給我帶來了一個NullPointer
錯誤,我看不出爲什麼。getLastKnownLocation returns NULL
下面的代碼被首先調用;
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個烤麪包那裏,他們回來精細與實際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;
}
}
我只是不知道爲什麼,當我嘗試檢索位置,這似乎已在被檢索方法,它只是提出一個空指針。
你混合新的API和老的getLastLocation遵循這一 https://stackoverflow.com/a/48033659/4997704 –