Похоже, что PendingIntent в Android Geofence Transition не запускается (реактивный мост) - PullRequest
0 голосов
/ 12 января 2019

Я следую руководству по Android Руководству по Android , чтобы построить простой нативный мост для реактивного натива для геозон.

Но я не получаю никакого ответа при входе или выходе из геозоны. Похоже, что PendingIntent / IntentService for Transitions работает неправильно.

Мой модуль выглядит в основном так. Он также создает mGeofenceList, как в документах, заполненных данными изact-native.

MyModule:

public class MyModule extends ReactContextBaseJavaModule {  

  //Build geofences
  private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
  }

  //Build pending intent
  private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
      return mGeofencePendingIntent;
    }
    Intent intent = new Intent(reactContext, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
    // calling addGeofences() and removeGeofences().
    mGeofencePendingIntent = PendingIntent.getService(reactContext, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
  }

  @ReactMethod
  public void startMonitoring() {
    mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
      .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
          Log.i(TAG, "Start Monitoring");
          postNotification("Start Monitoring", "Pressed Start Monitoring");
        }
      })
      .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
          Log.e(TAG, "Start Monitoring: " + e.getMessage());
        }
      });
  }
}

При запуске startMonitoring() создаются уведомление (Start Monitoring) и журнал, поэтому я предполагаю, что ошибка не в этой части.

IntentService также выглядит довольно просто / похоже на документы. IntentService:

public class GeofenceTransitionsIntentService extends IntentService {
    private static final String TAG = "GeofenceService";
    private Handler handler;
    SharedPreferences sp;

    public GeofenceTransitionsIntentService(){
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        handler = new Handler();
        Log.i(TAG, "Intent created");
    }


    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent");
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errorMessage = "Error Code: " + String.valueOf(geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);
            return;
        }

        // Get the transition type.
        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        // Test that the reported transition was of interest.
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            // Get the geofences that were triggered. A single event can trigger
            // multiple geofences.
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            // Get the transition details as a String.
            String geofenceTransitionDetails = getGeofenceTransitionDetails(
                    geofenceTransition,
                    triggeringGeofences
            );

            // Send notification and log the transition details.
            //sendNotification(geofenceTransitionDetails);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Enter/Exit", Toast.LENGTH_SHORT).show();
                }
            });
            Log.i(TAG, geofenceTransitionDetails);
        } else {
            // Log the error.
            Log.e(TAG, "Invalid transition");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /*
        Helpfunctions for logging
     */
    private String getGeofenceTransitionDetails(
            int geofenceTransition,
            List<Geofence> triggeringGeofences) {

        String geofenceTransitionString = getTransitionString(geofenceTransition);

        // Get the Ids of each geofence that was triggered.
        ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
        for (Geofence geofence : triggeringGeofences) {
            triggeringGeofencesIdsList.add(geofence.getRequestId());
        }
        String triggeringGeofencesIdsString = TextUtils.join(", ",  triggeringGeofencesIdsList);

        return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
    }
    private String getTransitionString(int transitionType) {
        switch (transitionType) {
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                return "entered Geofence";
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                return "exit Geofence";
            default:
                return "unknown Transition";
        }
    }
}

Но ни один из выходных данных этого класса не создается!

В манифесте моего родного модуля я добавил разрешение:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

И в манифесте TestApplication, использующего этот модуль, я также добавил это разрешение, а в тег приложения я добавил

<service android:name="com.mymodule.GeofenceTransitionsIntentService" android:exported="false"/>

Мне не удалось добавить эту последнюю строку в манифест модуля, поскольку в нем отсутствовал тег приложения и он не выполнял никаких действий. Я не уверен, что это правильное место.

Я тестирую в эмуляторе и меняю местоположение на список воспроизведения данных GPS.

Вопросы

  1. Как я могу убедиться, что ServiceIntent запущен? Могу ли я получить статус этого?
  2. Где появляются логи? В com.TestApplication или где-то еще?

и конечно: 3. Где моя ошибка?

1 Ответ

0 голосов
/ 13 января 2019

Хорошо, отвечаю на мой собственный вопрос или только на конкретный вопрос 3:

Приведенный выше код не содержит ошибок или, по крайней мере, работает должным образом на аппаратном устройстве.

Итак, как правильно отладить геозону на эмуляторе?

...