GPS的开发、使用,有两个关键点:

1. 选择并激活合适的Provider;

2. 建立合理刷新机制。

下面是通用的方法,以“选择并激活合适的Provider”:

protected void getAndTraceLocation(){//geocoder = new Geocoder(this, Locale.getDefault());;geocoder = new Geocoder(this, Locale.ENGLISH);;// Acquire a reference to the system Location ManagerlocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);Criteria criteria = new Criteria();criteria.setAccuracy(Criteria.ACCURACY_FINE);criteria.setAltitudeRequired(false);criteria.setBearingRequired(false);criteria.setCostAllowed(true);criteria.setPowerRequirement(Criteria.POWER_LOW);String provider = locationManager.getBestProvider(criteria, true);if(provider!=null){Log.i(TAG, "GPS provider is enabled:" + provider.toString());// Get the locationlatestLocation = locationManager.getLastKnownLocation(provider);updateWithNewLocation(latestLocation);// Register the listener with the Location Manager to receive locationlocationManager.requestLocationUpdates(provider, 1000, 5, locationListener);}else{Log.i(TAG, "No GPS provider found!");updateWithNewLocation(null);}}
protected final LocationListener locationListener = new LocationListener() {public void onLocationChanged(Location location) {Log.i(TAG, "location changed to: " + location);updateWithNewLocation(location);}public void onProviderDisabled(String provider) {}public void onProviderEnabled(String provider) {}public void onStatusChanged(String provider, int status, Bundle extras) {}};

需要注意的是:

这里的locationManager.getBestProvider(criteria, true) 之后,必须进行是否为null的判断,否则在终端禁用GPS和网络以后会出现NPE异常。

注意这里回调了一个通用的updateWithNewLocation(latestLocation)方法,用户只要实现这个方法,即可实现第二个关键点,即“建立合理刷新机制”。

下面是最简单的例子:

@Overrideprotected void updateWithNewLocation(Location location) {    super.updateWithNewLocation(location);    String location_msg = context.getString(R.string.msg_no_gps);if (location != null) {location_msg = location.getLatitude() + "," + location.getLongitude();Log.i(TAG, location_msg);} else {Log.i(TAG, location_msg);}location_msg = String.format(_location_msg, location_msg);_location.setText(location_msg);}

完毕!

更多相关文章

  1. Android之getSystemService方法实现详解
  2. 转:bitmap设置图片尺寸缩小,避免内存溢出/OutOfMemoryError的优化
  3. Android之——退出多个Activity
  4. Android-抽象类抽象方法
  5. Android(安卓)SimpleAdapter 的list刷新问题。
  6. 24、从头学Android之多媒体--使用MediaPlayer播放音频
  7. android--------自定义控件 之 方法篇
  8. android菜单menu详解
  9. Android(安卓)返回上一个界面刷新数据

随机推荐

  1. android 命令大全
  2. 如何将library项目打包成jar文件
  3. Android之开发BLE 详细步骤
  4. Android中shape的使用
  5. 关于用Android的API重写drawRegion方法的
  6. 2011.06.03(2)——— android 1.6 launcher
  7. android和ios button点击变暗效果
  8. android Intent使用
  9. Android系列之Post图片和数据
  10. Android中view的简单应用---随手指移动的