在官方程序中略为提及,但显然不够清楚,幸好官方有DemoApp,特将此代码提出。
1 添加LocationListerner变量
LocationListener mLocationListener = null; // create时注册此listener,Destroy时需要Remove
2 在OnCreate中注册定位监听器事件
mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
String strLog = String.format("您当前的位置:\r\n" + "纬度:%f\r\n"
+ "经度:%f", location.getLongitude(),
location.getLatitude());
TextView mainText = (TextView) findViewById(R.id.textview);
mainText.setText(strLog);
}
if (location != null) {
GeoPoint pt = new GeoPoint(
(int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6));
mMapView.getController().animateTo(pt);
}
}
};
3 添加MyLocationOverlay变量
MyLocationOverlay mLocationOverlay = null;
4 在OnCreate中添加该层
mLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mLocationOverlay);
5 最后在Activity重载两个函数
@Override
protected void onPause() {
// TODO Auto-generated method stub
HZBikeApp app = (HZBikeApp) this.getApplication();
app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
mLocationOverlay.disableMyLocation();
mLocationOverlay.disableCompass(); // 关闭指南针
app.mBMapMan.stop(); // 停止地图服务
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
HZBikeApp app = (HZBikeApp) this.getApplication();
app.mBMapMan.getLocationManager().requestLocationUpdates(
mLocationListener);
mLocationOverlay.enableMyLocation();
mLocationOverlay.enableCompass(); // 打开指南针
app.mBMapMan.start(); // 恢复地图服务
super.onResume();
}