Я хочу динамически обновлять список геозон в соответствии с текущим местоположением пользователя, даже если приложение не находится в фоновом режиме. Поэтому я звоню GeofencingApi.addGeofences из службы, а не из активности.
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);
}
}
Код для получения 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);
}
Код для получения GeofencingRequest:
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
Он не запускает GeofenceTransitionsIntentService, когда пользователь входит или выходит из геозоны. Он отлично работает при реализации в деятельности, но не работает из службы.
Примечание. Эти функции определены и вызываются в службе, которая динамически изменяет mGeofenceList в соответствии с текущим местоположением пользователя.
Изменить:
Манифест:
<?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
? КакaddGeoFences()
вызывается? Вы уверены, что его вызывают? - person David Wasser   schedule 16.09.2015