Android - GPS Location with Listener

/****
 * GPS Process
 *
 * First of all call listener of Location
 * then checking for GPS_PROVIDER
 * if not available then check for NETWORK_PROVIDER
 * and if its also not available then pass 0.00,0.00 to longitude and latitude
 *
 ****
 */
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}

public void onProviderEnabled(String provider) {
}

public void onProviderDisabled(String provider) {
}
};

// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// check if GPS enabled
if (isGPSEnabled) {

Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
// see http://www.androidsnippets.com/android-gps-location-with-listener
// Here i have created code for Android GPS Location to get longitude and latitude of current location and updated location.

Useful:

It'll give you default longitude and latitude using GPS_PROVIDER
If you don't have GPS online then it'll give latitude and longitude using NETWORK_PROVIDER.
If you don't have connection NETWORK_PROVIDER and GPS_PROVIDER than it'll return 0.00 for both latitude and longitude.

Comments

Popular posts from this blog

Android - Using KeyStore to encrypt and decrypt the data

Stack and Queue

Java Reflection API