Getting Latitude and Longitude 0.0 in Android M

11,117

Solution 1

With the help of CommonsWare and Blackkara answer, I was able to solve my problem.

As per their suggestion I have changed my code and have a look after each and every step of my code with debugging.

Due to that I came with the problem that my onLocationChanged() did not get fired in the case of Marshmallow but surprisingly, it gets fire in the case of older devices which are less than Android M or 6.0.

For solving this I have changed my code as below, here I am posting the full code so that anyone who has the same problem can get rid of it.

GPSTracker.java

public class GPSTracker extends Service{

    private  Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    Activity activity;

    public GPSTracker() {
    }

    public GPSTracker(Context context, Activity activity) {
        this.mContext = context;
        this.activity = activity;
        getLocation();
    }

    public Location getLocation() {
        try {


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

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

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    int requestPermissionsCode = 50;

                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
            // If GPS enabled, get latitude/longitude using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);

                    } else {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {

                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS() {

    }


    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {

            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }


    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

DashboardActivity.java

public class DashboardActivity extends Activity {      

    Context mContext;   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        mContext = this;

        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

        } else {
            Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show();
            gps = new GPSTracker(mContext, DashboardActivity.this);

            // Check if GPS enabled
            if (gps.canGetLocation()) {

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                // \n is for new line
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            } else {
                // Can't get location.
                // GPS or network is not enabled.
                // Ask user to enable GPS/network in settings.
                gps.showSettingsAlert();
            }
        }           
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the

                    // contacts-related task you need to do.

                    gps = new GPSTracker(mContext, DashboardActivity.this);

                    // Check if GPS enabled
                    if (gps.canGetLocation()) {

                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();

                        // \n is for new line
                        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    } else {
                        // Can't get location.
                        // GPS or network is not enabled.
                        // Ask user to enable GPS/network in settings.
                        gps.showSettingsAlert();
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                    Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}

Manifest.xml :

Permission which are added

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

Declare service in Application Tag:

 <service android:name=".utilities.GPSTracker"/>

Solution 2

You could be having below causes?

First cause

Location provider is not giving you 0.0 values as latitude and longitude. You are getting what had you define first time. Because, you didn't receive fresh location or getLastKnownLocation() returns null. So latitude and longitude variables keep their first values (0.0)

double latitude;
double longitude;

Second cause

Whenever you call getLocation() method, getLastKnownLocation() method will be doing nothing until onLocationChanged fire! (depending on provider)

@Override
public void onLocationChanged(Location location) {

}

Elaborated for 'depending on provider'

You have requested both gps and network providers.

requestLocationUpdates(LocationManager.NETWORK_PROVIDER ... mLocationListener);
requestLocationUpdates(LocationManager.GPS_PROVIDER ... mLocationListener);

And then has called getLastKnownLocation method for both two providers

locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

Assume that those two providers have returned null. In this case, you need to wait until onLocationChanged method has been fired. Otherwise you will be getting null from getLastKnownLocation method depending on provider

@Override
public void onLocationChanged(final Location location) {

    String providerName =  location.getProvider();

    if(providerName.equals(LocationManager.GPS_PROVIDER)){
        // onLocationChanged method is fired by gps provider.
        // After this point, getLastKnownLocation(); method returns not-null 
        // for LocationManager.GPS_PROVIDER
    }

    if( providerName.equals(LocationManager.NETWORK_PROVIDER)){
        // onLocationChanged method is fired by network provider.
        // After this point, getLastKnownLocation(); method returns not-null 
        // for LocationManager.NETWORK_PROVIDER
    }
}

Solution 3

First, remove these:

<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Those are defined by the platform, not you.

Also, you are not reacting when the user actually grants permission to you. Request the permissions in your activity, and do not create an instance of GPSTracker until you have permission. That may be immediately, if checkSelfPermission() says that you have permission. Otherwise, that will be when the activity is called with onRequestPermissionResult().

The location work itself is also buggy, in that you seem to think that you will get a location immediately, which will not be the case much of the time.

Share:
11,117

Related videos on Youtube

KishuDroid
Author by

KishuDroid

Leaders don't create followers.., They create more LEADERS..

Updated on June 04, 2022

Comments

  • KishuDroid
    KishuDroid about 2 years

    I am suffering from the problem of getting value 0.0 as latitude and longitude in Android Marshmallow (API 23) i.e. 6.0.

    I have searched a lot regarding this but didn't find solution of it. My code is fully working for the other API versions which are less than 23.

    I have also put the code for selfPermission and which all are working instead it's giving me 0.0 as late and long.

    Please have a look on the way I am following:

    GPSTracker.java

    public class GPSTracker extends Service implements LocationListener {
    
        private  Context mContext;
    
        // Flag for GPS status
        boolean isGPSEnabled = false;
    
        // Flag for network status
        boolean isNetworkEnabled = false;
    
        // Flag for GPS status
        boolean canGetLocation = false;
    
        Location location; // Location
        double latitude; // Latitude
        double longitude; // Longitude
    
        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; 
    
        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
        // Declaring a Location Manager
        protected LocationManager locationManager;
    
        Activity activity;
    
        public GPSTracker() {
        }
    
        public GPSTracker(Context context, Activity activity) {
            this.mContext = context;
            this.activity = activity;
            getLocation();
        }
    
        public Location getLocation() {
            try {
    
    
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
    
                // Getting GPS status
                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
                // Getting network status
                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
                if (!isGPSEnabled && !isNetworkEnabled) {
                    // No network provider is enabled
                } else {
                    this.canGetLocation = true;
                    if (isNetworkEnabled) {
                        int requestPermissionsCode = 50;
                        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestPermissionsCode);
    
                        } else {
                            locationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Network", "Network");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                    }
                    // If GPS enabled, get latitude/longitude using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
    
                            } else {
                                locationManager.requestLocationUpdates(
                                        LocationManager.GPS_PROVIDER,
                                        MIN_TIME_BW_UPDATES,
                                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                                Log.d("GPS Enabled", "GPS Enabled");
                                if (locationManager != null) {
                                    location = locationManager
                                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                    if (location != null) {
                                        latitude = location.getLatitude();
                                        longitude = location.getLongitude();
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return location;
        }
    
    
        /**
         * Stop using GPS listener
         * Calling this function will stop using GPS in your app.
         * */
        public void stopUsingGPS() {
            if (locationManager != null) {
                if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
    
                } else {
                    locationManager.removeUpdates(GPSTracker.this);
                }
    
    
            }
        }
    
    
        /**
         * Function to get latitude
         * */
        public double getLatitude(){
            if(location != null){
                latitude = location.getLatitude();
            }
    
            // return latitude
            return latitude;
        }
    
    
        /**
         * Function to get longitude
         * */
        public double getLongitude(){
            if(location != null){
                longitude = location.getLongitude();
            }
    
            // return longitude
            return longitude;
        }
    
        /**
         * Function to check GPS/Wi-Fi enabled
         * @return boolean
         * */
        public boolean canGetLocation() {
            return this.canGetLocation;
        }
    
    
        /**
         * Function to show settings alert dialog.
         * On pressing the Settings button it will launch Settings Options.
         * */
        public void showSettingsAlert(){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
    
            // Setting Dialog Title
            alertDialog.setTitle("GPS is settings");
    
            // Setting Dialog Message
            alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
    
            // On pressing the Settings button.
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });
    
            // On pressing the cancel button
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    
            // Showing Alert Message
            alertDialog.show();
        }
    
    
        @Override
        public void onLocationChanged(Location location) {
        }
    
    
        @Override
        public void onProviderDisabled(String provider) {
        }
    
    
        @Override
        public void onProviderEnabled(String provider) {
        }
    
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
     }
    

    DashboardActivity.java:

    In onCreate() I have initialized GPSTracker:

    gps = new GPSTracker(mContext,DashboardActivity.this);
    
            // Check if GPS enabled
            if(gps.canGetLocation()) {
    
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
    
                // \n is for new line
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            } else {
                // Can't get location.
                // GPS or network is not enabled.
                // Ask user to enable GPS/network in settings.
                gps.showSettingsAlert();
            }
    

    AndroidManifest.xml

    <permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />
    

    I have gone through many links provided in Stack Overflow but none of them helped me to solve this problem.

    I would appreciate any kind of help here.

    • Vivek Mishra
      Vivek Mishra about 8 years
      are you granting permission to app to access location?
    • KishuDroid
      KishuDroid about 8 years
      @VivekMishra: Yes I have granted for both the permission.
    • KishuDroid
      KishuDroid about 8 years
      @VivekMishra: Yes I have answered you for that
    • KishuDroid
      KishuDroid about 8 years
      @AndanHM: That was not my solution, but thanks for it.
  • KishuDroid
    KishuDroid about 8 years
    Let me try the way what you suggested.
  • KishuDroid
    KishuDroid about 8 years
    Still I am getting 0.0 as latitude and longitude. I have changed my code as you suggested but still not working :-(
  • KishuDroid
    KishuDroid about 8 years
    Depending on the provider, what does it mean? Can you please eloborate it?
  • blackkara
    blackkara about 8 years
    Edited the answer.
  • IntelliJ Amiya
    IntelliJ Amiya over 7 years
    Thanks for your work .First time lat,long showing 0.0 then okay
  • Sidhartha
    Sidhartha almost 7 years
    I have implemented your code , but still getting 0.0 in Marshmallow .
  • Selvin
    Selvin almost 6 years
    new GPSTracker(mContext, DashboardActivity.this) and GPSTracker extends Service ? this is not how we starting services on Android platform Declare service in Application Tag: what for? you never use this service in the right way, so service element is not necessary
  • jhfdr3s
    jhfdr3s almost 6 years
    shouldn't you need to call user-feature ? <uses-feature android:name="android.hardware.location.network" /> <uses-feature android:name="android.hardware.location.gps" />