I have seen various code snippets which find outs co-ordinates from various methods like onlocationupdate() or onstatusChanged().... what i want is a simple code that fetches my current GPS co-ordinates on click of a button...
Yogsma's answer addresses how to receive automatic updates. The link he references provides all you need, but here is the summarized version of how to do a manual update:
Assuming you've read the tutorials on how to make a button, then you simply need to add a listener for your button, and then have the listener call a function to query your location manager. The code below does it all inline to show you how, but I'd instantiate LocationManager somewhere else (eg your activity) and I'd create a separate method for the on click listener to call to perform the update.
// getLocationButton is the name of your button. Not the best name, I know.
getLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// instantiate the location manager, note you will need to request permissions in your manifest
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// get the last know location from your location manager.
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// now get the lat/lon from the location and do something with it.
nowDoSomethingWith(location.getLatitude(), location.getLongitude());
}
});
Of course you will also need to register your activity with the location manager service in your manifest xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
LocationManager mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocListener = new MyLocationListener();
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocListener);
public class MyLocationListener implements LocationListener{
public void onLocationChanged(Location loc) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
loc.getLongitude(), loc.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Read this for detail http://www.javacodegeeks.com/2010/09/android-location-based-services.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With