我打开地图活动后无法立即获取当前位置。 尽管它用蓝点标记显示当前位置。一旦我打开我的地图活动,就无法获取当前位置
我看到的异常信息:显示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
我对这个概念很陌生。这个怎么用? –
我是否必须更改完整的代码? –