Thursday, February 05, 2009

 

Minimal code to retreive a GPS location in Google Android

Here I describe the minimal code to retrieve a GPS location in the Google Android OS.

First up, a GPS location listener.
class GPSLocationListener implements LocationListener {

public void onLocationChanged(Location location) {       
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}

public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub 
}

public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub 
}  
}
Somewhere else, probably in the Activity you need to tie this listener in. Here is an onCreate from a minimal application's Activity.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

GPSLocationListener gpsLocationListener = new GPSLocationListener();

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

long minTime = 600000;
float minDistance = 10;

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsLocationListener);

}
minTime is a request to the OS about how often to check the GPS location. If you set it less than 1 minute (60000) then you risk the battery going flat quickly because the GPS receiver will be on all the time. The number is just a request. The OS may request a fix more often, it may check less often.

minDistance is a request to trigger the listener when the device has moved by this distance.

You also need <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in the applications AndroidManifest.xml file.

Labels:


Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]