Search code examples
androidgoogle-mapsgeolocationgpsandroid-gps

Get user current lat lng after GPS enabled - Android


I have followed this tutorial http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ for showing popup if GPS in not enabled and getting users current location.

And here is the broadcast receiver which listens to the GPS enabled disabled condition

private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            gps = new GPSTracker(getActivity());

            if(gps.canGetLocation()){
                Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());

                Toast.makeText(getActivity(), "GPS Switch", Toast.LENGTH_SHORT).show();

                if(gps.getLatitude() != 0 && gps.getLongitude() != 0 ){
                    final CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(gps.getLatitude(),gps.getLongitude()))      // Sets the center of the map to selected place
                            .zoom(15)                   // Sets the zoom
                            .build();                   //
                    gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                    Toast.makeText(getActivity(), "GPS Switch Lat: "+gps.getLatitude()+" Long: "+gps.getLongitude(), Toast.LENGTH_SHORT).show();
                }
            } else {
                if(!gps.isSettingDialogShown())
                    gps.showSettingsAlert();
            }
        }
    }
};

When I enable the GPS via settings dialog or from drop down menu. GPSTracker class gets the location service and checks for the user's current location in this code fragment

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) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();

                    }
                }
            }
            // 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", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                        }
                    }
                }
            }
        }

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

    return location;
}

Problem:

Firstly I don't know why broadcast receiver, receives the action two times and secondly when in normal mode lat lng value in receiver remains zero but in debugging sometimes it returns the value of users current location.

Can you please help what I am doing wrong?


Solution

  • If you don't need to work with Gps and Network Locations separately. I recommend to use FusedLocationProvider. BroadcastReceiver is probably working twice because it works for both gps and network location services