浏览 2594 次
锁定老帖子 主题:GPS在Android的使用
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-11-03
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 Manager locationManager = (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 location latestLocation = locationManager.getLastKnownLocation(provider); updateWithNewLocation(latestLocation); // Register the listener with the Location Manager to receive location locationManager.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)方法,用户只要实现这个方法,即可实现第二个关键点,即“建立合理刷新机制”。
下面是最简单的例子:
@Override protected 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); } 完毕! 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |