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);
}
完畢!