Android offers so many API to find the location till froyo version we had only request location updates and it will eat up the battery with continuous updates.
There is a new API introduced in 2.3 to obtain single update of GPS.
An simple example to obtain location (single update) is as below:
- Register a receiver to listen to intent – “SINGLE_LOCATION_UPDATE_ACTION”
registerReceiver(singleUpdateReceiver,new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));
- Get the instance of location manger service
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
- Create criteria instance and set accuracy as required
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW); - Create a pendingIntent instance. Pendingintent is registered to receive broadcast with action “SINGLE_LOCATION_UPDATE_ACTION” from the location manager
Intent updateIntent = new Intent(SINGLE_LOCATION_UPDATE_ACTION);
singleUpatePI = PendingIntent.getBroadcast(this, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT); - Finally, request for single update
locationManager.requestSingleUpdate(criteria, singleUpatePI);
- We need to declare the receiver with onReceive function as below
protected BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"onReceive");
//unregister the receiver so that the application does not keep listening the broadcast even after the broadcast is received.
context.unregisterReceiver(singleUpdateReceiver);// get the location from the intent send in broadcast using the key - this step is very very important
String key = LocationManager.KEY_LOCATION_CHANGED;
Location location = (Location)intent.getExtras().get(key);// Call the function required
if (location != null) {
onLocationChanged(location);
}// finally remove the updates for the pending intent
locationManager.removeUpdates(singleUpatePI);
}
};