Skip to content

Instantly share code, notes, and snippets.

@SlavaFir
Created March 26, 2019 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SlavaFir/83256975f578223e696b25ad3fe26f4c to your computer and use it in GitHub Desktop.
Save SlavaFir/83256975f578223e696b25ad3fe26f4c to your computer and use it in GitHub Desktop.
public class LocationActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(300000);
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(180000);
mGoogleApiClient = new GoogleApiClient.Builder(Context)
.addConnectionCallbacks(GoogleApiClient.ConnectionCallbacks)
.addOnConnectionFailedListener(
GoogleApiClient.OnConnectionFailedListener)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// Handle this according to the logic of your app
}
@Override
public void onConnected(Bundle arg0) {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (lastLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onDisconnected() {}
@Override
public void onLocationChanged(Location location) {
// doSomethingWithNewLocation(location);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment