GPS在Android的使用

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

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

2. 建立合理刷新机制。

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

Java代码 收藏代码
  1. protectedvoidgetAndTraceLocation(){
  2. //geocoder=newGeocoder(this,Locale.getDefault());;
  3. geocoder=newGeocoder(this,Locale.ENGLISH);;
  4. //AcquireareferencetothesystemLocationManager
  5. locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
  6. Criteriacriteria=newCriteria();
  7. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  8. criteria.setAltitudeRequired(false);
  9. criteria.setBearingRequired(false);
  10. criteria.setCostAllowed(true);
  11. criteria.setPowerRequirement(Criteria.POWER_LOW);
  12. Stringprovider=locationManager.getBestProvider(criteria,true);
  13. if(provider!=null){
  14. Log.i(TAG,"GPSproviderisenabled:"+provider.toString());
  15. //Getthelocation
  16. latestLocation=locationManager.getLastKnownLocation(provider);
  17. updateWithNewLocation(latestLocation);
  18. //RegisterthelistenerwiththeLocationManagertoreceivelocation
  19. locationManager.requestLocationUpdates(provider,1000,5,locationListener);
  20. }else{
  21. Log.i(TAG,"NoGPSproviderfound!");
  22. updateWithNewLocation(null);
  23. }
  24. }
Java代码 收藏代码
  1. protectedfinalLocationListenerlocationListener=newLocationListener(){
  2. publicvoidonLocationChanged(Locationlocation){
  3. Log.i(TAG,"locationchangedto:"+location);
  4. updateWithNewLocation(location);
  5. }
  6. publicvoidonProviderDisabled(Stringprovider){}
  7. publicvoidonProviderEnabled(Stringprovider){}
  8. publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){}
  9. };

需要注意的是:

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

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

下面是最简单的例子:

Java代码 收藏代码
  1. @Override
  2. protectedvoidupdateWithNewLocation(Locationlocation){
  3. super.updateWithNewLocation(location);
  4. Stringlocation_msg=context.getString(R.string.msg_no_gps);
  5. if(location!=null){
  6. location_msg=location.getLatitude()+","+location.getLongitude();
  7. Log.i(TAG,location_msg);
  8. }else{
  9. Log.i(TAG,location_msg);
  10. }
  11. location_msg=String.format(_location_msg,location_msg);
  12. _location.setText(location_msg);
  13. }

你可能感兴趣的:(android)