6

I am using the following code to get my current location. But the problem I am facing is, it always returns 0.0 for latitude and longitude. I have turned on the GPS settings in the phone and set all the permissions. But still I am facing this.

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

customLocationListener = new CustomLocationListener();

locationManager.requestLocationUpdates(

        LocationManager.GPS_PROVIDER,

        0,

        0,

        customLocationListener);

class CustomLocationListener implements LocationListener{ ............

      public void onLocationChanged(Location argLocation) { 

         if(location != null) {     

        int latitude=(int)(argLocation.getLatitude()*1E6);   

        int longitude=(int)(argLocation.getLongitude()*1E6);


              }
       } ........ }

Do any one of you know why?

Note : My activity extends MapActivity not Location Listener

tejas
  • 2,435
  • 10
  • 37
  • 54

5 Answers5

7

also check this is one of the reason. Go to maps default application and allow user to allow latitude and longitude option .In our application When the GPS signal blinks and when it stops we will get the latitude and longitude. This Worked for me


Edit 1

  1. Open Google Maps app and click button on map to get current location.

  2. When you allow Google map permission, then only other apps permission will work. (and I feel this is big bug)

  3. Now go to your app and try to get current location and it will work.

This is ugly, but we have follow those steps to get current location in our app.

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
Pradeep
  • 129
  • 3
  • 10
4

try this way

locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);


        Criteria locationCritera = new Criteria();
        String providerName = locationManager.getBestProvider(locationCritera,
                true);
        if(providerName!=null)
            location = locationManager.getLastKnownLocation(providerName);

        locationListener = new MyLocationListener();

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, locationListener);

in mylocationlistener set your location object

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location loc) {

        if (loc != null) {
            location = loc; 

        }
    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • @ Mayur Parekh...am getting null for location if I do location = locationManager.getLastKnownLocation(providerName); I got the value for provider as gps. – tejas Oct 04 '11 at 08:30
  • I got what the problem was, it was because the place where I sit was not receiving proper GPS connection..!! I tried in the emulator by hardcoding latitude and longitude, then it works. Inference: It is better to try in emulator for test to get the current location of user – tejas Oct 04 '11 at 09:29
  • Can you tell me, how to get the address of the user location i.e., not the coordinates rather the full address where he is currently staying – tejas Oct 04 '11 at 10:11
  • you should post this as a new question. anyways you can use the GeoCoder class Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List
    addresses = geocoder.getFromLocation(lat, lng, 1);
    – MKJParekh Oct 04 '11 at 11:06
  • Hi Erum, the code in accepted answer works fine. You can follow that.Make sure you are outside the building, sometimes if you check inside the building it may not work !! – tejas Feb 19 '15 at 06:05
4

Here is what you want..!

public void getCurrentLocation() {
        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(context);
        Criteria crta = new Criteria();
        crta.setAccuracy(Criteria.ACCURACY_FINE);
        crta.setAltitudeRequired(false);
        crta.setBearingRequired(false);
        crta.setCostAllowed(true);
        crta.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(crta, true);

        locationManager.requestLocationUpdates(provider, 1000, 0,
                new LocationListener() {
                    @Override
                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                    @Override
                    public void onLocationChanged(Location location) {
                        if (location != null) {
                            double lat = location.getLatitude();
                            double lng = location.getLongitude();
                            if (lat != 0.0 && lng != 0.0) {
                                System.out.println("WE GOT THE LOCATION");
                                System.out.println(lat);
                                System.out.println(lng);                                                         
                            }
                        }

                    }

                });
    }
Noby
  • 6,562
  • 9
  • 40
  • 63
  • @Noby... I tried, but am getting 0.0 in the line double lat = location.getLatitude(); So still my problem continued. – tejas Oct 04 '11 at 08:33
  • turn your gps off then try...! Make sure you given enough time to get your location details.(wait for five minutes). – Noby Oct 04 '11 at 09:01
1

Here, when we give a permission for location then after just wait for few seconds,GPS will take time for stable location ,after that we will get the actual values of lat and long.

Setting -> GPS Enable

Reason for lat long value comes 0.0

Priya
  • 289
  • 2
  • 14
1

CustomLocationManager.Java

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class CustomLocationManager {

    private LocationManager mLocationManager;
    private LocationValue locationValue;
    private Location networkLocation = null;
    private Location gpsLocation = null;

    private Timer mTimer;

    private boolean isGpsEnabled = false;
    private boolean isNetworkEnabled = false;

    private static CustomLocationManager _instance;

    private CustomLocationManager() {}

    public static CustomLocationManager getCustomLocationManager() {
        if (_instance == null) {
            _instance = new CustomLocationManager();
        }
        return _instance;
    }

    public LocationManager getLocationManager(Context context) {
        if (mLocationManager == null)
            mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return mLocationManager;
    }

    public boolean getCurrentLocation(Context context, LocationValue result) {
        locationValue = result;
        if (mLocationManager == null)
            mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        try {
            isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {}

        try {
            isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {}

        if (!isGpsEnabled && !isNetworkEnabled)
            return false;

        if (isGpsEnabled)
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);

        if (isNetworkEnabled)
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);

        mTimer = new Timer();
        mTimer.schedule(new GetLastKnownLocation(), 20000);

        return true;
    }

    LocationListener gpsLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            mTimer.cancel();
            locationValue.getCurrentLocation(location);
            mLocationManager.removeUpdates(this);
            mLocationManager.removeUpdates(networkLocationListener);
        }

        public void onProviderDisabled(String provider) {}

        public void onProviderEnabled(String provider) {}

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

    private LocationListener networkLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            mTimer.cancel();
            locationValue.getCurrentLocation(location);
            mLocationManager.removeUpdates(this);
            mLocationManager.removeUpdates(gpsLocationListener);
        }

        public void onProviderDisabled(String provider) {}

        public void onProviderEnabled(String provider) {}

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

    private class GetLastKnownLocation extends TimerTask {
        CurrentLocationHandler handler;

        GetLastKnownLocation() {
            handler = new CurrentLocationHandler();
        }

        @Override
        public void run() {
            mLocationManager.removeUpdates(gpsLocationListener);
            mLocationManager.removeUpdates(networkLocationListener);

            if (isGpsEnabled)
                gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (isNetworkEnabled)
                networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            handler.sendEmptyMessage(0);
        }
    }

    private class CurrentLocationHandler extends Handler {
        @Override
        public final void handleMessage(Message msg) {
            if (gpsLocation != null && networkLocation != null) {

                if (gpsLocation.getTime() > networkLocation.getTime())
                    locationValue.getCurrentLocation(gpsLocation);
                else
                    locationValue.getCurrentLocation(networkLocation);

                return;
            }

            if (gpsLocation != null) {
                locationValue.getCurrentLocation(gpsLocation);
                return;
            }

            if (networkLocation != null) {
                locationValue.getCurrentLocation(networkLocation);
                return;
            }

            locationValue.getCurrentLocation(null);
        }
    }
}


LocationValue.Java

import android.location.Location;

public abstract class LocationValue {
    public abstract void getCurrentLocation(Location location);
}


YourActivity.Java

private void getCurrentLocation() {
        CustomLocationManager.getCustomLocationManager().getCurrentLocation(this, locationValue);
    }

    public LocationValue locationValue = new LocationValue() {
        @Override
        public void getCurrentLocation(Location location) {
            // You will get location here if the GPS is enabled
            if(location != null) {
                Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
            }
        }
    };
  • Here, when we give a permission for location then after just wait for few seconds,GPS will take time for stable location ,after that we will get the actual values of lat and long. – Priya Jan 01 '18 at 08:51
  • Working perfect... Good Solution – Ketan Ramani Apr 13 '20 at 05:26