Skip to content Skip to sidebar Skip to footer

Can't Get Gps Current Location's Latitude And Longitude Android

I am trying to get Current Location using either GPS or Network Provider. My device's GPS is enabled but I'm not getting Latitude and Longitude. GpsTracker.java: public class GpsTr

Solution 1:

MainActivity:

import android.location.Address;
import android.location.Location;
import com.example.havadurumumenu.MyLocationManager.LocationHandler;

publicclassMainActivityextendsActivityimplementsLocationHandler{

    publicMyLocationManager locationManager;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(newOnClickListener() {
            @OverridepublicvoidonClick(View v) {
                currentLocation();              
            }
        });
    }

    publicvoidcurrentLocation(){

        locationManager = newMyLocationManager();
        locationManager.setHandler(this);

        boolean isBegin = locationManager.checkProvidersAndStart(getApplicationContext());
        if(isBegin){
            //if at least one of the location providers are on it comes into this part.
        }else{
            //if none of the location providers are on it comes into this part.
        }

    }

    @OverridepublicvoidlocationFound(Location location) {
        Log.d("LocationFound", ""+location);

        //you can reach your Location here//double latitude = location.getLatitude(); //double longtitude = location.getLongitude();

        locationManager.removeUpdates();
    }

    @OverridepublicvoidlocationTimeOut() {
        locationManager.removeUpdates();

         //you can set a timeout in MyLocationManager class

        txt.setText("Unable to locate. Check your phone's location settings");
    }

MyLocationManager:

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/*---------- Listener class to get coordinates ------------- */publicclassMyLocationManagerimplementsLocationListener {

    publicLocationManager locationManager;
    publicLocationHandler handler;
    privateboolean isLocationFound = false;

    publicMyLocationManager() {}

    publicLocationHandlergetHandler() {
        return handler;
    }

    publicvoidsetHandler(LocationHandler handler) {
        this.handler = handler;
    }
    @SuppressLint("HandlerLeak")
    publicbooleancheckProvidersAndStart(Context context){
        boolean isBegin = false;

        Handler stopHandler = newHandler(){
            publicvoidhandleMessage(Message msg){
                if (!isLocationFound) {
                        handler.locationTimeOut();
                }
            }
        };
        stopHandler.sendMessageDelayed(newMessage(), 15000);

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

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1000, this);
            isBegin = true;
        }
        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1000, this);
            isBegin = true;
        }
        return isBegin;     
    }

    publicvoidremoveUpdates(){
        locationManager.removeUpdates(this);
    }
    /**
     * To get city name from coordinates
     * @param location is the Location object
     * @return city name
     */publicStringfindCity(Location location){
        /*------- To get city name from coordinates -------- */String cityName = null;
        Geocoder gcd = newGeocoder(AppController.getInstance(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            cityName = addresses.get(0).getLocality();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return cityName;
    }

    @OverridepublicvoidonLocationChanged(Location loc) {
        isLocationFound = true;
        handler.locationFound(loc);
    }

    @OverridepublicvoidonProviderDisabled(String provider) {}

    @OverridepublicvoidonProviderEnabled(String provider) {}

    @OverridepublicvoidonStatusChanged(String provider, int status, Bundle extras) {}

    publicinterfaceLocationHandler{
        publicvoidlocationFound(Location location);
        publicvoidlocationTimeOut();
    }
}

Also add all the permissions below in your Manifest.xml

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

Solution 2:

I Solved by exchanging position of both methods.

First app trying to get location using GPS if GPS is not enabled then using network provider method.

publicclassGpsTrackerextendsServiceimplementsLocationListener {

privatefinal Context mContext;

// flag for GPS StatusbooleanisGPSEnabled=false;
// flag for network statusbooleanisNetworkEnabled=false;
booleancanGetLocation=false;
Location location;
publicdouble latitude;
publicdouble longitude;

// The minimum distance to change updates in mettersprivatestaticfinallongMIN_DISTANCE_CHANGE_FOR_UPDATES=10; // 10// metters// The minimum time beetwen updates in millisecondsprivatestaticfinallongMIN_TIME_BW_UPDATES=1000 * 60 * 1; // 1 minute// Declaring a Location Managerprotected LocationManager locationManager;

publicGpsTracker(Context context) {
    this.mContext = context;
    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 GPS Enabled get lat/long using GPS Servicesif (isGPSEnabled) {
            if (location == null) {
                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();
                    }
                }
            }
            // if Network Provider Enabled get lat/long using GPS Servicesif (isNetworkEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        updateGPSCoordinates();
                    }
                }
            }


        }

    } catch (Exception e) {
        // e.printStackTrace();
        Log.e("Error : Location",
                "Impossible to connect to LocationManager", e);
    }

    return location;
}

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

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

    return latitude;
}

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

    return longitude;
}

}

Post a Comment for "Can't Get Gps Current Location's Latitude And Longitude Android"