Created
June 17, 2017 12:27
-
-
Save mumayank/aaf85c5375f606d8095a096a50a892f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LocationIntentService extends IntentService { | |
private GoogleApiClient mGoogleApiClient; | |
public LocationIntentService() { | |
super(LocationIntentService.class.getName()); | |
} | |
@Override | |
protected void onHandleIntent(Intent intent) { | |
initGoogleApiClient(); | |
} | |
private void initGoogleApiClient() { | |
final LocationListener locationListener = new LocationListener() { | |
@Override | |
public void onLocationChanged(Location location) { | |
// location received successfully | |
} | |
}; | |
final GoogleApiClient.ConnectionCallbacks connectionCallbacks = new GoogleApiClient.ConnectionCallbacks() { | |
@Override | |
public void onConnected(@Nullable Bundle bundle) { | |
LocationRequest mLocationRequest = LocationRequest.create(); | |
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); // You may set different values depending on your use case | |
//mLocationRequest.setInterval(10000); // If you want to get location updates (1000 = 1 sec interval) | |
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener); | |
// Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); | |
// you have location here as well, but I would suggest you wait for the location listener's result | |
} | |
@Override | |
public void onConnectionSuspended(int i) { | |
// location fetch failed | |
} | |
}; | |
GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() { | |
@Override | |
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { | |
// location fetch failed | |
} | |
}; | |
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) | |
.addConnectionCallbacks(connectionCallbacks) | |
.addOnConnectionFailedListener(onConnectionFailedListener) | |
.addApi(LocationServices.API) | |
.build(); | |
if (!mGoogleApiClient.isConnected()) { | |
mGoogleApiClient.connect(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment