我打開地圖活動後無法立即獲取當前位置。 儘管它用藍點標記顯示當前位置。一旦我打開我的地圖活動,就無法獲取當前位置
我看到的異常信息:顯示java.lang.NullPointerException:嘗試調用虛擬方法「雙android.location.Location.getLatitude()」上的空對象引用
這需要大量的時間來獲取座標。爲此,我必須移動手機並等待。
這是我爲它的代碼:
if (Build.VERSION.SDK_INT < 25) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Ask for permission
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
lastKnownLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
pDialog.hide();
locate = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("Your Location")
.position(locate)));
origin_lati = "" + lastKnownLocation.getLatitude();
origin_longi = "" + lastKnownLocation.getLongitude();
Log.e("Lati Longi", origin_lati+", "+origin_longi);
}catch (Exception e){
Log.e("Exception", e.toString());
}
}
}
爲什麼不使用新的fusedLocationApi進行位置更新? – sumit
我對這個概念很陌生。這個怎麼用? –
我是否必須更改完整的代碼? –