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. }

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 【Android(安卓)开发教程】使用Intent传递数据
  3. Android(安卓)用纯代码实现复杂界面
  4. Android让屏幕保持常亮,不熄屏的三种方法
  5. EventBus3.0源码解析(二):post()与postSticky()
  6. android将path拆分为多个path
  7. Android(安卓)利用getIdentifier()方法获取资源ID
  8. android activity-alias 的作用
  9. 《第一行代码-Android》学习笔记(八)

随机推荐

  1. Android(安卓)NDK编译时出现的问题以及解
  2. 第一章:初入Android大门(程序加载应用)
  3. Android中ListView异步加载数据
  4. android 验证码 (canvas)
  5. Android(安卓)永久隐藏导航栏,系统栏的方
  6. Android(安卓)SDK Manager设置代理服务器
  7. android文件解析InputStream问题解决
  8. android 中,关于线程安全退出的问题(from s
  9. Android(安卓)— 创建和修改 Fragment 的
  10. android:visibility