Skip to content

Instantly share code, notes, and snippets.

@SlavaFir

SlavaFir/LocationActivity.java Secret

Created Mar 26, 2019
Embed
What would you like to do?
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