How to get the coarse location using Wifi or GSM or GPS, whichever is available?

27,352

Solution 1

Here's a certain point of view:

private void _getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) 
            getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}

This might however request a FINE_LOCATION access. So:

Another way is to use this which uses the LocationManager.

The quickest possible way is to use the Last Known location with this, I used it and it's quite fast:

private double[] getGPS() {
 LocationManager lm = (LocationManager) getSystemService(
  Context.LOCATION_SERVICE);
 List<String> providers = lm.getProviders(true);

 Location l = null;

 for (int i=providers.size()-1; i>=0; i--) {
  l = lm.getLastKnownLocation(providers.get(i));
  if (l != null) break;
 }

 double[] gps = new double[2];
 if (l != null) {
  gps[0] = l.getLatitude();
  gps[1] = l.getLongitude();
 }

 return gps;
}

Solution 2

This is one way

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;

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

    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 (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    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 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();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            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/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch 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 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 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;
    }

}

Use it this way:

gps = new GPSTracker(PromotionActivity.this);

// check if GPS enabled     
if(gps.canGetLocation()){
    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
    gps.showSettingsAlert();    
}

Using this, you can get the best location available. hope that helps

Solution 3

you can use LocationClient it provides a unified/simplified (Fused) location API, check out this Video for introductory material and background or this developer guide

the main drawback is that you make you app dependent on the existence of Google Play Services on the device.

Solution 4

In order to get info from specific provider you should use: LocationManager.getLastKnownLocation(String provider), if you want your app to choose automatically between providers then you can add choosing of the provider with getBestProvider method. As for stopping refreshing of GPS location, I didn't quite catch. Do you need to get the location info only once or do you need to monitor location changes periodically?

EDIT: Oh by the way, if you want your location info to be up-to-date you should use requestSingleUpdate method of location manager, with specified Criteria. In this case provider should also be chosen automatically

Share:
27,352
Sibbs Gambling
Author by

Sibbs Gambling

Updated on July 18, 2020

Comments

  • Sibbs Gambling
    Sibbs Gambling almost 4 years

    My app only needs a coarse location service when started up.

    In detail, I need the app's rough location so as to provide the users with the shop info nearby.

    The location does NOT need to be updated constantly. In addition, coarse localization will be sufficient in this case.

    I wish the app to choose GSM, or wifi, or GPS automatically, whichever is available.

    The location service should also be one-time to save phone energy.

    How may I do that?

    I have tried using GPS separately.

    My problem is I don't know how to stop the constantly-refreshing-location feature of GPS. I don't know how to make the phone select one out of the three methods, either.

    Some sample codes or ideas are greatly appreciated.

  • Sibbs Gambling
    Sibbs Gambling almost 11 years
    only once. i.e. the app estimates the location only when it is first started. Later the user may manually choose to refresh teh location
  • Samir
    Samir about 7 years
    Need to be carefull with "this" keyword in order to call from other Activity needed to be replace with "mContext"