Не удалось инициировать переход IntentService геозоны из PendingIntent

Я хочу динамически обновлять список геозон в соответствии с текущим местоположением пользователя, даже если приложение не находится в фоновом режиме. Поэтому я звоню 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>


person Tushar Kathuria    schedule 12.09.2015    source источник
comment
Неважно, откуда вы регистрируете геозоны (Активность, Сервис и т. д.). Я предполагаю, что вы прошли через developer.android.com/intl/ja/training /location/geofencing.html — у меня работает — повторите эти шаги и проверьте свой код.   -  person Marian Paździoch    schedule 14.09.2015
comment
Опубликуйте свой манифест, пожалуйста.   -  person David Wasser    schedule 14.09.2015
comment
@MarianPaździoch Вы тестировали это с помощью службы? Обновляется ли список геозон новыми геозонами, даже если приложение не находится в фоновом режиме? Моя цель — получить информацию о близлежащих местах из Places API, а затем использовать эти данные для обновления списка геозон каждый раз, когда пользователь меняет местоположение, независимо от того, находится ли приложение в фоновом режиме.   -  person Tushar Kathuria    schedule 16.09.2015
comment
@DavidWasser Я опубликовал свой манифест.   -  person Tushar Kathuria    schedule 16.09.2015
comment
Вы не опубликовали весь свой манифест. Есть ли в вашем приложении какие-либо действия? Как вы начинаете Service? Как addGeoFences() вызывается? Вы уверены, что его вызывают?   -  person David Wasser    schedule 16.09.2015
comment
Что значит приложение не в фоне?   -  person Marian Paździoch    schedule 16.09.2015
comment
Что вы подразумеваете под обновлением списка Geofence?   -  person Marian Paździoch    schedule 16.09.2015
comment
Решил? Не могли бы вы взглянуть на этот вопрос, пожалуйста?   -  person Skizo-ozᴉʞS    schedule 04.10.2015
comment
@Skizo Не удалось решить, поэтому я изменил свою стратегию. Теперь я обновляю список геозон только тогда, когда пользователь запускает приложение.   -  person Tushar Kathuria    schedule 05.10.2015


Ответы (1)


Например: https://developer.android.com/training/location/geofencing.html с кодом: https://github.com/googlesamples/android-play-location/tree/master/Geofencing

Использовать:

 mGoogleApiClient.blockingConnect(TIME_OUT, TimeUnit.MILLISECONDS);

И добавьте/измените код следующим образом:

public class RegisterGeoIntentService extends IntentService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {

protected static final String TAG = "RegisterGeoIS";

private static final long TIME_OUT = 100;
protected GoogleApiClient mGoogleApiClient;
protected ArrayList<Geofence> mGeofenceList;
private PendingIntent mGeofencePendingIntent;

public RegisterGeoIntentService() {
    super(TAG);
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "Creating Intent service");
    mGeofenceList = new ArrayList<Geofence>();
    mGeofencePendingIntent = null;
}

@Override
protected void onHandleIntent(Intent intent) {
    buildGoogleApiClient();
    populateGeofenceList();
    mGoogleApiClient.blockingConnect(TIME_OUT, TimeUnit.MILLISECONDS);
    String connected = mGoogleApiClient.isConnected() ? "connected" : "disconnected";
    Log.i(TAG, "Restoring geofence - status: " + connected);
    addGeofencesButtonHandler();
}

...

public void addGeofencesButtonHandler() {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                // The GeofenceRequest object.
                getGeofencingRequest(),
                // A pending intent that that is reused when calling removeGeofences(). This
                // pending intent is used to generate an intent when a matched geofence
                // transition is observed.
                getGeofencePendingIntent()
        ).await(TIME_OUT, TimeUnit.MILLISECONDS);
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
        logSecurityException(securityException);
    }
    Log.i(TAG, "Trying to add Geofences - result: " + result.toString());
}

...

Добавьте следующее в AndroidManifest:

    <service android:name=".RegisterGeoIntentService" />

Назовите это с помощью:

    Intent kickoff = new Intent(context, RegisterGeoIntentService.class);
    context.startService(kickoff);
person powder366    schedule 14.12.2015