GPS在Android的使用
16lz
2021-01-25
GPS的开发、使用,有两个关键点:
1. 选择并激活合适的Provider;
2. 建立合理刷新机制。
下面是通用的方法,以“选择并激活合适的Provider”:
Java代码- protectedvoidgetAndTraceLocation(){
- //geocoder=newGeocoder(this,Locale.getDefault());;
- geocoder=newGeocoder(this,Locale.ENGLISH);;
- //AcquireareferencetothesystemLocationManager
- locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
- Criteriacriteria=newCriteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setAltitudeRequired(false);
- criteria.setBearingRequired(false);
- criteria.setCostAllowed(true);
- criteria.setPowerRequirement(Criteria.POWER_LOW);
- Stringprovider=locationManager.getBestProvider(criteria,true);
- if(provider!=null){
- Log.i(TAG,"GPSproviderisenabled:"+provider.toString());
- //Getthelocation
- latestLocation=locationManager.getLastKnownLocation(provider);
- updateWithNewLocation(latestLocation);
- //RegisterthelistenerwiththeLocationManagertoreceivelocation
- locationManager.requestLocationUpdates(provider,1000,5,locationListener);
- }else{
- Log.i(TAG,"NoGPSproviderfound!");
- updateWithNewLocation(null);
- }
- }
- protectedfinalLocationListenerlocationListener=newLocationListener(){
- publicvoidonLocationChanged(Locationlocation){
- Log.i(TAG,"locationchangedto:"+location);
- updateWithNewLocation(location);
- }
- publicvoidonProviderDisabled(Stringprovider){}
- publicvoidonProviderEnabled(Stringprovider){}
- publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){}
- };
需要注意的是:
这里的locationManager.getBestProvider(criteria, true) 之后,必须进行是否为null的判断,否则在终端禁用GPS和网络以后会出现NPE异常。
注意这里回调了一个通用的updateWithNewLocation(latestLocation)方法,用户只要实现这个方法,即可实现第二个关键点,即“建立合理刷新机制”。
下面是最简单的例子:
Java代码- @Override
- protectedvoidupdateWithNewLocation(Locationlocation){
- super.updateWithNewLocation(location);
- Stringlocation_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);
- }
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- 【Android(安卓)开发教程】使用Intent传递数据
- Android(安卓)用纯代码实现复杂界面
- Android让屏幕保持常亮,不熄屏的三种方法
- EventBus3.0源码解析(二):post()与postSticky()
- android将path拆分为多个path
- Android(安卓)利用getIdentifier()方法获取资源ID
- android activity-alias 的作用
- 《第一行代码-Android》学习笔记(八)