Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location android android

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location


You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if block. Similar to-

if( !isGPSEnabled && !isNetworkEnabled) {// Can't get location by any way} else {    if(isGPSEnabled) {    // get location from GPS    } else if(isNetworkEnabled) {    // get location from Network Provider    }}

So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.

EDIT:

To make it better, I'll post a snippet. Consider it is in try-catch:

boolean gps_enabled = false;boolean network_enabled = false;LocationManager lm = (LocationManager) mCtx                .getSystemService(Context.LOCATION_SERVICE);gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Location net_loc = null, gps_loc = null, finalLoc = null;if (gps_enabled)    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);if (network_enabled)    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);if (gps_loc != null && net_loc != null) {    //smaller the number more accurate result will    if (gps_loc.getAccuracy() > net_loc.getAccuracy())         finalLoc = net_loc;    else        finalLoc = gps_loc;        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)} else {    if (gps_loc != null) {        finalLoc = gps_loc;    } else if (net_loc != null) {        finalLoc = net_loc;    }}

Now you check finalLoc for null, if not then return it.You can write above code in a function which returns the desired (finalLoc) location. I think this might help.


The recommended way to do this is to use LocationClient:

First, define location update interval values. Adjust this to your needs.

private static final int MILLISECONDS_PER_SECOND = 1000;private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;private static final int FASTEST_INTERVAL_IN_SECONDS = 1;private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

Have your Activity implement GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, and LocationListener.

public class LocationActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {}

Then, set up a LocationClientin the onCreate() method of your Activity:

public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    mLocationClient = new LocationClient(this, this, this);    mLocationRequest = LocationRequest.create();    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);    mLocationRequest.setInterval(UPDATE_INTERVAL);    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);}

Add the required methods to your Activity; onConnected() is the method that is called when the LocationClientconnects. onLocationChanged() is where you'll retrieve the most up-to-date location.

@Overridepublic void onConnectionFailed(ConnectionResult connectionResult) {    Log.w(TAG, "Location client connection failed");}@Overridepublic void onConnected(Bundle dataBundle) {    Log.d(TAG, "Location client connected");    mLocationClient.requestLocationUpdates(mLocationRequest, this); }@Overridepublic void onDisconnected() {    Log.d(TAG, "Location client disconnected");}@Overridepublic void onLocationChanged(Location location) {    if (location != null) {        Log.d(TAG, "Updated Location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()));    } else {        Log.d(TAG, "Updated location NULL");    } }     

Be sure to connect/disconnect the LocationClient so it's only using extra battery when absolutely necessary and so the GPS doesn't run indefinitely. The LocationClient must be connected in order to get data from it.

public void onResume() {    super.onResume();    mLocationClient.connect();}public void onStop() {    if (mLocationClient.isConnected()) {        mLocationClient.removeLocationUpdates(this);    }    mLocationClient.disconnect();    super.onStop();}

Get the user's location. First try using the LocationClient; if that fails, fall back to the LocationManager.

public Location getLocation() {    if (mLocationClient != null && mLocationClient.isConnected()) {        return mLocationClient.getLastLocation();    } else {        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);        if (locationManager != null) {            Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);            if (lastKnownLocationGPS != null) {                return lastKnownLocationGPS;            } else {                return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);            }        } else {            return null;        }    }}


use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately.

package com.example.ashis.gpslocation;import android.app.Activity;import android.location.Location;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.widget.TextView;import android.widget.Toast;import com.google.android.gms.common.ConnectionResult;import com.google.android.gms.common.GooglePlayServicesUtil;import com.google.android.gms.common.api.GoogleApiClient;import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;import com.google.android.gms.location.LocationListener;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationServices;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** * Location sample. * * Demonstrates use of the Location API to retrieve the last known location for a device. * This sample uses Google Play services (GoogleApiClient) but does not need to authenticate a user. * See https://github.com/googlesamples/android-google-accounts/tree/master/QuickStart if you are * also using APIs that need authentication. */public class MainActivity extends Activity implements LocationListener,        GoogleApiClient.ConnectionCallbacks,        GoogleApiClient.OnConnectionFailedListener {    private static final long ONE_MIN = 500;    private static final long TWO_MIN = 500;    private static final long FIVE_MIN = 500;    private static final long POLLING_FREQ = 1000 * 20;    private static final long FASTEST_UPDATE_FREQ = 1000 * 5;    private static final float MIN_ACCURACY = 1.0f;    private static final float MIN_LAST_READ_ACCURACY = 1;    private LocationRequest mLocationRequest;    private Location mBestReading;TextView tv;    private GoogleApiClient mGoogleApiClient;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        if (!servicesAvailable()) {            finish();        }        setContentView(R.layout.activity_main);tv= (TextView) findViewById(R.id.tv1);        mLocationRequest = LocationRequest.create();        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);        mLocationRequest.setInterval(POLLING_FREQ);        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addApi(LocationServices.API)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .build();        if (mGoogleApiClient != null) {            mGoogleApiClient.connect();        }    }    @Override    protected void onResume() {        super.onResume();        if (mGoogleApiClient != null) {            mGoogleApiClient.connect();        }    }    @Override    protected void onPause() {d        super.onPause();        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {            mGoogleApiClient.disconnect();        }    }        tv.setText(location + "");        // Determine whether new location is better than current best        // estimate        if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {            mBestReading = location;            if (mBestReading.getAccuracy() < MIN_ACCURACY) {                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);            }        }    }    @Override    public void onConnected(Bundle dataBundle) {        // Get first reading. Get additional location updates if necessary        if (servicesAvailable()) {            // Get best last location measurement meeting criteria            mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);            if (null == mBestReading                    || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY                    || mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);               //Schedule a runnable to unregister location listeners                    @Override                    public void run() {                        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);                    }                }, ONE_MIN, TimeUnit.MILLISECONDS);            }        }    }    @Override    public void onConnectionSuspended(int i) {    }    private Location bestLastKnownLocation(float minAccuracy, long minTime) {        Location bestResult = null;        float bestAccuracy = Float.MAX_VALUE;        long bestTime = Long.MIN_VALUE;        // Get the best most recent location currently available        Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);        //tv.setText(mCurrentLocation+"");        if (mCurrentLocation != null) {            float accuracy = mCurrentLocation.getAccuracy();            long time = mCurrentLocation.getTime();            if (accuracy < bestAccuracy) {                bestResult = mCurrentLocation;                bestAccuracy = accuracy;                bestTime = time;            }        }        // Return best reading or null        if (bestAccuracy > minAccuracy || bestTime < minTime) {            return null;        }        else {            return bestResult;        }    }    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {    }    private boolean servicesAvailable() {        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);        if (ConnectionResult.SUCCESS == resultCode) {            return true;        }        else {            GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();            return false;        }    }}