Below given snippet. API client connection need to be done before starting the geo fencing request.
public int onStartCommand(Intent intent, int flags, int startId)
{
if(mGeofenceList == null)
{
mGeofenceList = new ArrayList();
}
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId("HOME_GF")
.setCircularRegion(12.841022,
77.6480388,
100
)
.setExpirationDuration(600000 * 6)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
buildGoogleApiClient();
mGoogleApiClient.connect();
return START_REDELIVER_INTENT;
}
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeoFenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(LOG_TAG, "Connected to GoogleApiClient");
Toast.makeText(AppUtils.getAppContext(), "Connected to GoogleApiClient", Toast.LENGTH_SHORT).show();
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(LOG_TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
String info = "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode();
Toast.makeText(AppUtils.getAppContext(), info , Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason.
Log.i(LOG_TAG, "Connection suspended");
Toast.makeText(AppUtils.getAppContext(), "Connection suspended" , Toast.LENGTH_SHORT).show();
// onConnected() will be called again automatically when the service reconnects
}
References:
No comments:
Post a Comment