Get continuous location using service even after app killed from recent drawer

1.7k views Asked by At

I started Service from main activity like;-

Intent intent = new Intent(this, MyLocationService.class);
startService(intent);

MyLocationService class looks like:-

public class MyLocationService extends Service implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    private static final String TAG = MyLocationService.class.getSimpleName();
    public static Location mCurrentLocation;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: ");
        initiateGooglePlayService();
    }
    public void initiateGooglePlayService() {
        Log.e(TAG, "initiateGooglePlayService: ");
        if (isGooglePlayServicesAvailable()) {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(5000);
            mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setSmallestDisplacement(10.0f);
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mGoogleApiClient.connect();
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ");
        return null;
    }
    private boolean isGooglePlayServicesAvailable() {
        Log.e(TAG, "isGooglePlayServicesAvailable: ");
        int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext());
        return ConnectionResult.SUCCESS == status;
    }
    @Override
    public void onConnected(Bundle bundle) {
        Log.e(TAG, "onConnected: ");
        startLocationUpdates();
    }
    @Override
    public void onConnectionSuspended(int i) {
        Log.e(TAG, "onConnectionSuspended: ");
    }
    protected void startLocationUpdates() {
        Log.e(TAG, "startLocationUpdates: ");
        try {
            PendingResult<Status> pendingResult;
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        } catch (IllegalStateException ignored) {
        }
    }
    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: " + location.getLongitude());
        if (mGoogleApiClient.isConnected()) {
            mCurrentLocation = location;
            Intent intent = new Intent("GPSLocationUpdates");
            intent.putExtra("location", location);
         LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Toast.makeText(this, "location", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(TAG, "onConnectionFailed: ");
    }
}

I never stop the service anywhere.

But still I am unable to get the control of onLocationChange().

My motive is that, I need continuous location to do some background operation. It worked in lollipop sometimes. But it is not working in Marshmallow and nougat and even kitkat also. I searched but could not get the proper idea. Please let me know, where i am going wrong. Any suggestion accepted.

I am using following dependency for location;-

 compile 'com.google.android.gms:play-services-location:9.6.1'
2

There are 2 answers

4
yash786 On
/**Check out my Github post i did the same for Taxi clone**/

Link ---> https://github.com/yash786agg/GPS/

Note: Remember to remove or comment the below mentioned code if you want the latitude 
and latitude even when the application is in background.

    if(networkUtilObj != null)
    {
        networkUtilObj.disconnectGoogleApiClient();
    }
1
Aman Jain On

You can use the HyperTrack SDK to get the location updates in the background. Get more insight about the reliability of SDK here in different conditions.

First Setup the SDK

After setting up the SDK you just need to set the Callback to receive the location updates.

HyperTrack.setCallback(new HyperTrackEventCallback() {
@Override
public void onEvent ( @NonNull final HyperTrackEvent event){
    switch (event.getEventType()) {
        case HyperTrackEvent.EventType.LOCATION_CHANGED_EVENT:
            Log.d(TAG, "onEvent: Location Changed");
            HyperTrackLocation hyperTrackLocation = event.getLocation();
            LatLng latLng = hyperTrackLocation.getLatLng();
            updateCurrentLocationMarker(event.getLocation());
            break;
    }
}
}

(Disclaimer: I work at HyperTrack.)