By using the below code we can get the current latitude and longitude in android application.
Below are the imports need to be added
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.StrictMode;
Below are the variable need to add
String latitude,longitude;
LocationManager locManager;
Location location;
add the below code in the on create method
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria,true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location==null){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
.setMessage("Unable to find location please check your GPS connection").setTitle(
"Alert");
dialogBuilder.setPositiveButton("OK",
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
dialogBuilder.create().show();
}
else{
latitude = Double.toString(location.getLatitude());
longitude= Double.toString(location.getLongitude());
}
Usually in the emulator we need to set the longitude and latitudes through the command prompt using adb shell or we need to set using the ddms perspective.