Can't Get GPS Current Location's Latitude

2019-09-21 12:00发布

问题:

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 GpsTracker extends Service implements LocationListener {

        private final Context mContext;
        // flag for GPS Status
        boolean isGPSEnabled = false; 
        // flag for network status
        boolean isNetworkEnabled = false;
        boolean canGetLocation = false; 
        Location location;
        public double latitude;
        public double longitude;

        // The minimum distance to change updates in metters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 
         // metters

         // 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;

                    public GpsTracker(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 Network Provider Enabled get lat/long using GPS Services
                                if (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();
                                        }
                                    }   
                                }

                                 // if GPS Enabled get lat/long using GPS Services
                                if (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();
                                            }
                                        }
                                    } 
                                }

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

                        return location;
                    }

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

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

                        return latitude;
                    }

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

                        return longitude;
                    }
                }

Service.Java

    public class WifiScaningService extends IntentService {

        GpsTracker gpsTracker;
        double latitude;
            double longitude;
        public WifiScaningService() {
                super("WifiScaningService"); 

            }

            @Override 
            public IBinder onBind(Intent intent) {    
                // TODO: Return the communication channel to the service.
                throw new UnsupportedOperationException("Not yet implemented");
            }

            @Override
            public void onCreate() {
                Log.e("service call","service call");
            }  


            @Override
            protected void onHandleIntent(Intent intent) {

            } 
            @Override


            public int onStartCommand(Intent intent, int flags, int startId) { 
                    Log.i("LocalService", "Received start id " + startId + ": " + intent);

                    gpsTracker = new GpsTracker(this); 
                    String stringLatitude = String.valueOf(gpsTracker.latitude);
                    latitude = Double.parseDouble(stringLatitude);
                    Log.e("Latitude",stringLatitude);
                    String stringLongitude = String.valueOf(gpsTracker.longitude);
                    longitude = Double.parseDouble(stringLongitude);
                    Log.e("Longitude",stringLongitude); 

                return START_STICKY;
            }
    }

I have included necessary permissions in AndroidManifest.xml file. Required to show current 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"/>

回答1:

MainActivity:

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

public class MainActivityextends Activity implements LocationHandler{

    public MyLocationManager locationManager;

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

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                currentLocation();              
            }
        });
    }

    public void currentLocation(){

        locationManager = new MyLocationManager();
        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.
        }

    }

    @Override
    public void locationFound(Location location) {
        Log.d("LocationFound", ""+location);

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

        locationManager.removeUpdates();
    }

    @Override
    public void locationTimeOut() {
        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 ------------- */
public class MyLocationManager implements LocationListener {

    public LocationManager locationManager;
    public LocationHandler handler;
    private boolean isLocationFound = false;

    public MyLocationManager() {}

    public LocationHandler getHandler() {
        return handler;
    }

    public void setHandler(LocationHandler handler) {
        this.handler = handler;
    }
    @SuppressLint("HandlerLeak")
    public boolean checkProvidersAndStart(Context context){
        boolean isBegin = false;

        Handler stopHandler = new Handler(){
            public void handleMessage(Message msg){
                if (!isLocationFound) {
                        handler.locationTimeOut();
                }
            }
        };
        stopHandler.sendMessageDelayed(new Message(), 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;     
    }

    public void removeUpdates(){
        locationManager.removeUpdates(this);
    }
    /**
     * To get city name from coordinates
     * @param location is the Location object
     * @return city name
     */
    public String findCity(Location location){
        /*------- To get city name from coordinates -------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(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;
    }

    @Override
    public void onLocationChanged(Location loc) {
        isLocationFound = true;
        handler.locationFound(loc);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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

    public interface LocationHandler{
        public void locationFound(Location location);
        public void locationTimeOut();
    }
}

Also add all the permissions below in your Manifest.xml

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


回答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.

public class GpsTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;

// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters

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

// Declaring a Location Manager
protected LocationManager locationManager;

public GpsTracker(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 Services
        if (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 Services
            if (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;
}

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

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

    return latitude;
}

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

    return longitude;
}

}


标签: android gps