实现Android的不同精度的定位(基于网络和GPS)

解决方案:

实现Android的不同精度的定位(基于网络和GPS)


Android中的定位服务的相关类基本上都在android.location包中,其中位置服务管理器(LocationManager)提供了定位功能所需要的API,下面是实现定位方法的关键部分:
1、实例化位置服务管理器的方法如下:
//变量定义
private LocationManager locationManager;
//得到LocationManager
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
2、开启位置服务的监听
有了LocationManager之后,我们就可以开始监听位置的变化了。我们使用LocationManager中的方法:
locationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) 
(上述参数说明:
Parameters
provider the name of the provider with which to register
minTime the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance the minimum distance interval for notifications, in meters
listener a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update)

来设置监听器。注意到第1个参数,这个参数的值为2选1,分别是:
LocationManager.NETWORK_PROVIDER
LocationManager.GPS_PROVIDER
前者用于移动网络中获取位置,精度较低但速度很快,后者使用GPS进行定位,精度很高但一般需要10-60秒时间才能开始第1次定位,如果是在室内则基本上无法定位。
开启位置改变监听代码:
private LocationListener gpsListener=null;
private LocationListener networkListner=null;
private void registerLocationListener(){
networkListner=new MyLocationListner();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, networkListner);
gpsListener=new MyLocationListner();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, gpsListener);
}
通过getLastKnownLocation(String provider)传对应参数,此时得到的Location并非当前的GPS位置信息,而是上一次获取到的位置信息,而requestLocationUpdates才是真正去请求位置信息的更新。
3、位置查询条件如精度等的设置方法
private Criteria getCriteria(){
Criteria criteria=new Criteria();
//设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 
criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
//设置是否要求速度
criteria.setSpeedRequired(false);
// 设置是否允许运营商收费 
criteria.setCostAllowed(false);
//设置是否需要方位信息
criteria.setBearingRequired(false);
//设置是否需要海拔信息
criteria.setAltitudeRequired(false);
// 设置对电源的需求 
criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
return criteria;
}
4、停止位置改变监听
只需要调用LocationManager对象的removeUpdates(LocationListener listener)方法就可以停止监听。

参考链接:
http://blog.sina.com.cn/s/blog_74c22b210100sfix.html
http://fzlihui.iteye.com/blog/713050
http://www.learningandroid.net/blog/foundation/tutorial-location-service/
http://www.cnblogs.com/jh5240/archive/2012/09/08/2676863.html

posted @ 2014-12-04 15:15  skyyhu  阅读(2291)  评论(0编辑  收藏  举报