Skip to content Skip to sidebar Skip to footer

How To Use Google Location Service Api To Get Location Updates Even In Background?

First of all this is not a duplicate of any other question on the site. I've seen location updates using Service and Google API both. Here is the link which uses the service to g

Solution 1:

Try:

Service.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
 import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationServices;


import java.io.IOException;
import java.io.OutputStreamWriter;

publicclassGPSServiceextendsServiceimplementsGoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {



private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;

@Nullable@Overridepublic IBinder onBind(Intent intent) {
    returnnull;
}


@OverridepublicvoidonCreate() {
    super.onCreate();

    mGoogleApiClient = newGoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

}

@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {

    mGoogleApiClient.connect();

    returnsuper.onStartCommand(intent, flags, startId);
}

@OverridepublicvoidonDestroy() {


    mGoogleApiClient.disconnect();
    super.onDestroy();



}


@OverridepublicvoidonConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second

    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

@OverridepublicvoidonConnectionSuspended(int i) {
    Toast.makeText(this,"GoogleApiClient connection has been suspend",Toast.LENGTH_LONG).show();
}

@OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"GoogleApiClient connection has failed",Toast.LENGTH_LONG).show();
}

and MainActivity.java

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intenti=newIntent(this,GPSService.class);
    startService(i);


}

Post a Comment for "How To Use Google Location Service Api To Get Location Updates Even In Background?"