I want to dynamically update the list of geofences according to current location of user even when app is not in background. So I am calling GeofencingApi.addGeofences from a service instead of activity.
public void addGeofences()
{
if (!mGoogleApiClient.isConnected()) {
Log.v("TAG", getString(R.string.not_connected));
return;
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent(this)
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
logSecurityException(securityException);
}
}
Code to get PendingIntent:
private PendingIntent getGeofencePendingIntent(Context c) {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(GeofenceService.this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Code to get GeofencingRequest:
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
It does not trigger GeofenceTransitionsIntentService when user enters or exits a geofence. It works very fine when implemented in activity but it does not work from service.
Note: These functions are defined and called in a service which is dynamically changing mGeofenceList according to current location of user.
Edit:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.routein" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<permission
android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
.....
<service android:name=".geofencing.GeofenceTransitionsIntentService" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="--My Api Key--" />
.....
</application>
Service
? How isaddGeoFences()
getting called? Are you sure it is getting called? – David Wasser