abhishek ameta abhishek ameta - 1 year ago 248
Android Question

onLocationChanged() never called

I am writing a code that brings current location but it is not giving me the location because it never calls

.Is there any way to find the location.

mobileLocation is coming 0 for this case, so the execution goes to the else block.

My code is

public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;

public FindLocation(Context ctx){
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
public void onProviderEnabled(String provider) {
public void onProviderDisabled(String provider) {
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
if (mobileLocation != null) {
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
} else {
System.out.println("in find location 4");
Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();

Answer Source

Do you never get a location or only as you write in your comment "sometimes it gets location but not at the time of click."?

Might be that your code is faster than LocationManager, which might not yet have called onLocationChanged(). Change your code in order to get the last known location, or wait until your locListener was called:

  LocationManager.GPS_PROVIDER, 1000, 1, locListener);
mobileLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download