[英]Android Google Maps Api v2 current Location Null
白天好,我正在尝试通过map.getMyLocation()
获取当前位置,但是肯定是由于一段时间未加载而导致NullPointerException。所以我正在做一次MapReady检查和MapLoaded检查,一旦地图准备就绪,它们都会触发并加载了它,但是不幸的是我的当前位置如何,似乎我永远都不知道它何时可用。这是我的代码的一个片段,尽管我可以进行常规的空检查。
@Override
public void onMapLoaded() {
//here my map is loaded so this triggers.
if(map.getMyLocation()!=null){
//do something here.
}
}
但是似乎我的空检查将永远不会工作,因为我上面编写的方法一旦触发它就不会等待我的if条件,它只是检查它是否不满足我的if条件而已,因此我的if条件永远不会触发。我什至试图将其放入while()
循环中while()
但是如果我在UI thread
上执行它会冻结,并且如果我在THREAD
上做任何事情都不会让我做什么需要在MainThread
上完成。因此,我的问题是下一个,如何在世界范围内通知我位置是否为空?一旦不为NULL
,如何触发某些代码?
我在应用程序中使用此代码。
尝试在您的应用中实施
//Global Declaration
GoogleMap googleMap;
LocationManager locationManager;
Location location;
CameraUpdate cameraUpdate;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
location = googleMap.getMyLocation();
if (location != null) {
LatLng latLang = new LatLng(location.getLatitude(), location.getLongitude());
cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLang, 17);
googleMap.animateCamera(cameraUpdate);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MapScreen.this);
builder.setTitle("Warning");
builder.setMessage("Location Not Found...!!!");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
} else {
showAlertDialog();
}
private void showAlertDialog () {
AlertDialog.Builder builder = new AlertDialog.Builder(MapScreen.this);
builder.setTitle("Warning");
builder.setMessage("Device GPS is currently OFF. Please Turn ON.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.