I need to get my current location using GPS programmatically. How can i achieve it?
LocationManager is a class that provides in-build methods to get last know location
STEP 1 :Create a LocationManager Object as below
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
STEP 2 : Add Criteria
*Criteria is use for setting accuracy*
Criteria criteria = new Criteria();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(true);
}
STEP 3 :GET Avaliable Provider
Threre are two types of provider GPS and network
String provider = locationManager.getBestProvider(criteria, true);
STEP 4: Get Last Know Location
Location location = locationManager.getLastKnownLocation(provider);
STEP 5: Get Latitude and Longitude
If location object is null then dont try to call below methods
getLatitude and getLongitude is methods which returns double values