大家自然会想到,不能直接获取,那就加listener,三板斧嘛,当然是有加监听的,如下代码,其中 LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER 分别为利用手机gps和利用蜂窝网络获取。这里要使用gps,因为蜂窝网络会发生漂移。(如果有朋友只是定位大体位置的话,可以用network,这个效率和速度都会更快) private LocationManager locationManager;
private void initListener() {
if (locationManager == null) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 1,locationGpsListener);
}那么,这个locationGpsListener里面具体要做什么,下面这段代码已经可以基本解答你的疑惑了。 /**
* location的监听。
*/
private MLocationListener locationGpsListener = new MLocationListener() {
// 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
@Override
public void onLocationChanged(Location mlocation) {
if (mlocation != null) {
if (!isPause) {// 如果没有暂停,则记录数据。
if (mMoveGpsDataList != null && mMoveGpsDataList.size() >= 1) {
speed = mlocation.getSpeed();
double latitude = mlocation.getLatitude();
double longitude = mlocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Logger.e(LTAG, "B_latLng : " + latLng.latitude + "," + latLng.longitude);
//google坐标转百度坐标。
latLng = gpsToBaidu(latLng);
PositionBean lastPosition = mMoveGpsDataList.getLast();
// 如果位置和上一次记录的位置点相同,则认为没有移动。
if (lastPosition.latlng.latitude != latLng.latitude
|| lastPosition.latlng.longitude != latLng.longitude) {
// 计算移动距离,和速度。
PositionBean oncePosition = getMoveGpsData(lastPosition, latLng);
if (oncePosition == null) {
showToast("点漂移了一次!");
} else {
mPointListWithGps.add(latLng);
mMoveGpsDataList.add(oncePosition);
mListGpsLocationAdapter.update(mMoveGpsDataList);
updateListenerView();
}
} else {
Logger.e(LTAG, "未移动,LocationSpeed : " + speed);
if (onces % 10 == 0) {
showToast("未移动,LocationSpeed : " + speed);
onces = 0;
}
onces++;
}
} else {
firstGetLocation(mlocation);
}
} else {// 如果暂停了,则toast提示。
showToast("位置改变了一次,暂停状态未记录!");
}
}
}
};你可能也注意到了,里面有个方法,gpsToBaidu(latLng);这个是应该就是坐标转换的了,具体的实现如下:
|