2013-09-13 7 views
3

Я успешно добавил геозон с флагом NEVER_EXPIRE. И все, кажется, работает нормально.Android Geofence Автоматически удаляется, когда служба определения местоположения отключена/перезапущена

Но теперь, тестируя, я обнаружил, что если я остановлю работу геолокации, службы перестанут работать как ОЖИДАЕМЫЕ. Далее, когда я снова запускаю службы определения местоположения, мой ранее добавленный геосферу снова должен начать работать, но никаких уведомлений не генерируется, и кажется, что геозонность автоматически удаляется после отключения служб определения местоположения. И я должен снова установить все местоположения, чтобы вернуть геозонность в рабочее состояние.

Любые предложения или любая идея, почему это так происходит?

EDIT ::

Аналогичный вопрос также рассматривается, когда устройство выключено/перезапущен и т.д. Таким образом, в основном все геозоны, которые зарегистрированы, будут удалены, если Location Services отключена/перезапуска устройства. Немногие из которых я пытался обработать с помощью сеанса, но я ищу решение, с помощью которого мы можем установить Geofences обратно, когда служба определения местоположения включена.

+0

Я могу подтвердить, что если местоположение услуг отключены, то все зарегистрированные геозоны удаляются. [link] (http://swebytes.com/2013/10/31/how-to-remove-old-geofences-generated-by-your-android-app/) @ b-ryce –

ответ

1

этого ответа ::: http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html

В случае поставщик сетевого расположения отключен пользователем, служба геозоны прекратит обновление, все зарегистрированные геозон будут удалены и намерение генерируются при условии отложенного намерения , В этом случае hasError (Intent) возвращает true, а getErrorCode (Intent) возвращает GEOFENCE_NOT_AVAILABLE.

Теперь :::: Как мы можем зарегистрировать Geofence назад, когда служба расположение назад .. (на заднем плане)

+0

Выяснил способ сделать это в фоновом режиме. Но нужно изменить GeofenceRequester.java, в этом случае мы изменили аргумент функции GeofenceRequester (final Activity Activity_name) на GeofenceRequester (конечное контекстное имя контекста), через это мы могли бы передать контекст для добавления геозонности с фона или с переднего плана. Я надеюсь, что это поможет –

5

Для просмотра в фоновом режиме, у меня был тот же вопрос и был в состоянии решить ее изменение кода образца из IntentService в BroadcastReceiver. Все подробности можно найти на моем посту здесь:

Android Geofence eventually stop getting transition intents

Это то, что я сказал (в случае, если кто слишком ленив, чтобы следовать по ссылке):

Таким образом, после игры вокруг с этим немного , похоже, что ReceiveTransitionsIntentService, как определено в примере кода, перестанет получать уведомления, когда приложение не существует. Я думаю, что это большая проблема с примером кода ... Похоже, что это полетят туда, как я.

Так что вместо этого я использовал широковещательный приемник, и до сих пор он, похоже, работает из моих тестов.

Добавьте к этому манифесту:

<receiver android:name="com.aol.android.geofence.GeofenceReceiver" 
     android:exported="false"> 
     <intent-filter > 
      <action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/> 
     </intent-filter> 
    </receiver> 

Тогда в классе GeofenceRequester вам нужно изменить метод createRequestPendingIntent так, что он идет к вашему BroadcastReceiver вместо ReceiveTransitionsIntentService

private PendingIntent createRequestPendingIntent() { 

     // If the PendingIntent already exists 
     if (null != mGeofencePendingIntent) { 

      // Return the existing intent 
      return mGeofencePendingIntent; 

     // If no PendingIntent exists 
     } else { 

      // Create an Intent pointing to the IntentService 
      Intent intent = new Intent("com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"); 
//   Intent intent = new Intent(context, ReceiveTransitionsIntentService.class); 
      /* 
      * Return a PendingIntent to start the IntentService. 
      * Always create a PendingIntent sent to Location Services 
      * with FLAG_UPDATE_CURRENT, so that sending the PendingIntent 
      * again updates the original. Otherwise, Location Services 
      * can't match the PendingIntent to requests made with it. 
      */ 
      return PendingIntent.getBroadcast(
        context, 
        0, 
        intent, 
        PendingIntent.FLAG_UPDATE_CURRENT); 
     } 
    } 

Затем я добавил класс GeofenceReceiver, который выглядит примерно так:

public class GeofenceReceiver extends BroadcastReceiver { 
    Context context; 

    Intent broadcastIntent = new Intent(); 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     this.context = context; 

     broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES); 

     if (LocationClient.hasError(intent)) { 
      handleError(intent); 
     } else { 
      handleEnterExit(intent); 
     } 
    } 

    private void handleError(Intent intent){ 
     // Get the error code 
     int errorCode = LocationClient.getErrorCode(intent); 

     // Get the error message 
     String errorMessage = LocationServiceErrorMessages.getErrorString(
       context, errorCode); 

     // Log the error 
     Log.e(GeofenceUtils.APPTAG, 
       context.getString(R.string.geofence_transition_error_detail, 
         errorMessage)); 

     // Set the action and error message for the broadcast intent 
     broadcastIntent 
       .setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR) 
       .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, errorMessage); 

     // Broadcast the error *locally* to other components in this app 
     LocalBroadcastManager.getInstance(context).sendBroadcast(
       broadcastIntent); 
    } 


    private void handleEnterExit(Intent intent) { 
     // Get the type of transition (entry or exit) 
     int transition = LocationClient.getGeofenceTransition(intent); 

     // Test that a valid transition was reported 
     if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER) 
       || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) { 

      // Post a notification 
      List<Geofence> geofences = LocationClient 
        .getTriggeringGeofences(intent); 
      String[] geofenceIds = new String[geofences.size()]; 
      String ids = TextUtils.join(GeofenceUtils.GEOFENCE_ID_DELIMITER, 
        geofenceIds); 
      String transitionType = GeofenceUtils 
        .getTransitionString(transition); 

      for (int index = 0; index < geofences.size(); index++) { 
       Geofence geofence = geofences.get(index); 
       ...do something with the geofence entry or exit. I'm saving them to a local sqlite db 

      } 
      // Create an Intent to broadcast to the app 
      broadcastIntent 
        .setAction(GeofenceUtils.ACTION_GEOFENCE_TRANSITION) 
        .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES) 
        .putExtra(GeofenceUtils.EXTRA_GEOFENCE_ID, geofenceIds) 
        .putExtra(GeofenceUtils.EXTRA_GEOFENCE_TRANSITION_TYPE, 
          transitionType); 

      LocalBroadcastManager.getInstance(MyApplication.getContext()) 
        .sendBroadcast(broadcastIntent); 

      // Log the transition type and a message 
      Log.d(GeofenceUtils.APPTAG, transitionType + ": " + ids); 
      Log.d(GeofenceUtils.APPTAG, 
        context.getString(R.string.geofence_transition_notification_text)); 

      // In debug mode, log the result 
      Log.d(GeofenceUtils.APPTAG, "transition"); 

      // An invalid transition was reported 
     } else { 
      // Always log as an error 
      Log.e(GeofenceUtils.APPTAG, 
        context.getString(R.string.geofence_transition_invalid_type, 
          transition)); 
     } 
    } 

    /** 
    * Posts a notification in the notification bar when a transition is 
    * detected. If the user clicks the notification, control goes to the main 
    * Activity. 
    * 
    * @param transitionType 
    *   The type of transition that occurred. 
    * 
    */ 
    private void sendNotification(String transitionType, String locationName) { 

     // Create an explicit content Intent that starts the main Activity 
     Intent notificationIntent = new Intent(context, MainActivity.class); 

     // Construct a task stack 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 

     // Adds the main Activity to the task stack as the parent 
     stackBuilder.addParentStack(MainActivity.class); 

     // Push the content Intent onto the stack 
     stackBuilder.addNextIntent(notificationIntent); 

     // Get a PendingIntent containing the entire back stack 
     PendingIntent notificationPendingIntent = stackBuilder 
       .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Get a notification builder that's compatible with platform versions 
     // >= 4 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(
       context); 

     // Set the notification contents 
     builder.setSmallIcon(R.drawable.ic_notification) 
       .setContentTitle(transitionType + ": " + locationName) 
       .setContentText(
         context.getString(R.string.geofence_transition_notification_text)) 
       .setContentIntent(notificationPendingIntent); 

     // Get an instance of the Notification manager 
     NotificationManager mNotificationManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 

     // Issue the notification 
     mNotificationManager.notify(0, builder.build()); 
    } 
} 

Надеюсь, это поможет кому-то еще.

+0

Я вернулся к тому же сообщению, которое я поднял и забыл ... В любом случае Спасибо за ответ .. –

+0

Однако, в моем случае он отлично работал, даже когда приложение было в фоновом режиме. Но основная проблема заключалась в том, что при переключении служб определения местоположения на устройство вы получите сообщение об ошибке ReceiveTransitionsIntentService, через которое может быть что-то может быть сделано для сброса Geofences и т. Д. Что я сделал, я удалил свою сессию и установил ее на Reset geofences обратно, когда пользователь возвращается к приложению. Я ищу решение, в котором пользователю не нужно возвращаться к приложению, и мы устанавливаем геофонность в фоновом режиме. –

0

@rns.Рави - посмотри, что говорят документы - вы должны зарегистрировать намерение, где вы могли бы затем повторно добавить все геозоны

public void requestLocationUpdates (LocationRequest request, PendingIntent callbackIntent) 

Requests location updates with a callback on the specified PendingIntent. 

This method is suited for the background use cases, more specifically for receiving location updates, even when the app has been killed by the system. In order to do so, use a PendingIntent for a started service. For foreground use cases, the LocationListener version of the method is recommended, see requestLocationUpdates(LocationRequest, LocationListener). 

Any previous LocationRequests registered on this PendingIntent will be replaced. 

Location updates are sent with a key of KEY_LOCATION_CHANGED and a Location value on the intent. 

Parameters 
request The location request for the updates. 
callbackIntent A pending intent to be sent for each location update. 
+0

Я создал приемника местоположения, который обновляет меня с каждым обновлением местоположения и от слушателя. Я вызываю службу, которая проверяет, Geofences Set или мне нужно сбросить Geofences. Все отлично, но теперь, когда я пытаюсь добавить Geofences из службы, это не возможно, потому что для добавления Geofences мне требуется передать Activity GeofenceRequester (), что невозможно из Сервиса. Теперь, как это можно решить? –

Смежные вопросы