Android提供了多种位置服务:
(1)GPS(使用卫星的全球定位系统);
(2)网络(用Cell-ID来进行基站定位,WI-FI服务地址)
(3)被动(API等级8加入)
在没有特别要求下,可以设置更新的频率,减少请求次数。注册监听器,在不用时,禁止位置监听
//接受位置更新
private void requestLocationUpdates() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> provider = lm.getAllProviders(); if (provider != null && !provider.isEmpty()) { LocationListener listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } }; for (String name : provider) { lm.requestLocationUpdates(name, DateUtils.HOUR_IN_MILLIS * 1, 100, listener);// 设置更新的频率 } } } // 注销监听器(用户可以强制固定某个位置),在需要调用的地方调用 private void disableLocationListener(LocationListener listener) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(listener); } //最后已知位置(不需要启动定位服务) private Location getLastKnownLocation(){ LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> names = lm.getAllProviders(); Location location=null; if(names!=null){ for(String name:names){ if(!LocationManager.PASSIVE_PROVIDER.equals(name)){ Location l=lm.getLastKnownLocation(name); if((l!=null)&&(location==null|| l.getTime()>location.getTime())){ location=l; } } } } return location; }
原文地址:http://blog.csdn.net/woyaochenggong774/article/details/45075603