M.Yogeshwaran
M.Yogeshwaran

Reputation: 1469

How to get Location updates even when gps is turned off using fused location API?

This question may be asked many time but I couldn't find any solution for it. I need to get the user's location in background for ever 15 min.

It works fine when the GPS is turned on but when the GPS is turned off, the app is not getting location updates. I need it to get at least the network location or wifi location.

How can I achieve this with fused location API.?

Location manager has this functionality but in fused location. Because Google suggests developers use Location from the play services API, I don't want to use location manager. How can I achieve this so let me post what I tried so far:

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * Created by 4264 on 14-10-2016.
 */

public class Locationlistener implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener  {


    private Location mlocation; // location
    private double latitude; // latitude
    private double longitude; // longitude
    private GoogleApiClient mGAC;
    private Context mContext;
    public static final String TAG = "GPSresource";
    private FusedLocationProviderApi fusedLocationProviderApi;
    private LocationRequest locationRequest;

    public Locationlistener(Context c)
    {
        mContext = c;
        try {
            buildGoogleApiClient();
            mGAC.connect();
        }
        catch(Exception e)
        {
            Log.d(TAG,e.toString());
        }
    }

    protected synchronized void buildGoogleApiClient() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
        locationRequest.setInterval(1);
        locationRequest.setFastestInterval(1);
        mGAC = new GoogleApiClient.Builder(mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
       }


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

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (mlocation != null) {
            longitude = mlocation.getLongitude();
        }

        // return longitude
        return longitude;
    }

    public Location GetLocationBlocking() throws InterruptedException {



        //      String lat=String.valueOf(moCurrentLocation.getLatitude());
        //    String longt=String.valueOf(moCurrentLocation.getLongitude());
//        Toast.makeText(oContext,"Lat"+lat+"long"+longt,Toast.LENGTH_SHORT).show();
        return mlocation;

    }


    @Override
    public void onConnected(Bundle bundle) {
            Location oLocation = LocationServices.FusedLocationApi.getLastLocation(mGAC);
            if (mGAC != null) {

                mlocation = oLocation;
            getLatitude();
            getLongitude();
            if (oLocation != null){
              Log.d("lat",String.valueOf(mlocation.getLatitude()));
            Log.d("long",String.valueOf(mlocation.getLongitude()));
            }
            else{
                LocationServices.FusedLocationApi.requestLocationUpdates(mGAC, locationRequest, this);
        }   }}


    @Override
    public void onConnectionSuspended(int i) {

    }




    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mlocation=location;
    }
}

Upvotes: 2

Views: 4057

Answers (1)

mohammadreza khalifeh
mohammadreza khalifeh

Reputation: 1618

i don't understand when you saying you don't want use location manager and GPS...look at this Location Strategies... based on this doc we have 3 strategy to access location:

  1. Gps
  2. Network Location Provider
  3. or using both

but for your location problem this is my offer: Inside an Activity, put the following to connect and start receiving location updates:

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

private long UPDATE_INTERVAL = 10 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create the location client to start receiving updates
    mGoogleApiClient = new GoogleApiClient.Builder(this)
                          .addApi(LocationServices.API)
                          .addConnectionCallbacks(this)
                          .addOnConnectionFailedListener(this).build();
}

protected void onStart() {
    super.onStart();
    // Connect the client.
    mGoogleApiClient.connect();
}

protected void onStop() {
    // Disconnecting the client invalidates it.
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    // only stop if it's connected, otherwise we crash
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onStop();
}

public void onConnected(Bundle dataBundle) {
    // Get last known recent location. 
    Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    // Note that this can be NULL if last location isn't already known.
    if (mCurrentLocation != null) {
      // Print current location if not null
      Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
      LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
    }
    // Begin polling for new location updates.
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
    if (i == CAUSE_SERVICE_DISCONNECTED) {
      Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
    } else if (i == CAUSE_NETWORK_LOST) {
      Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
    }
}

// Trigger new location updates at interval
protected void startLocationUpdates() {
    // Create the location request
    mLocationRequest = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        .setInterval(UPDATE_INTERVAL)
        .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
        mLocationRequest, this);
}

and then register for location updates with onLocationChanged:

public void onLocationChanged(Location location) {
    // New location has now been determined
    String msg = "Updated Location: " +
        Double.toString(location.getLatitude()) + "," +
        Double.toString(location.getLongitude());
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    // You can now create a LatLng Object for use with maps
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}

For more information on the Fused Location API, refer to Make ypur app Location Aware Troubleshooting Location Updates

Location updates should always be done using the GoogleApiClient leveraging the LocationServices.API as shown above. Do not use the older Location APIs which are much less reliable. Even when using the correct FusedLocationApi, there are a lot of things that can go wrong. Consider the following potential issues:

  • Did you add the necessary permissions? Make sure your app has INTERNET and ACCESS_COARSE_LOCATION permissions to ensure that location can be accessed as illustrated in the guide above.
  • Are you getting null when calling LocationServices.FusedLocationApi.getLastLocation? This is normal since this method only returns if there is already a location recently retrieved by another application. If this returns null, this means you need start receiving location updates with LocationServices.FusedLocationApi.requestLocationUpdates before receiving the location as shown above.
  • Are you trying to get location on the genymotion emulator? Ensure you've enabled GPS and configured a lat/lng properly. Try restarting the emulator if needed and re-enabling GPS or trying a device (or the official emulator) instead to rule out genymotion specific issues.

Upvotes: 2

Related Questions