2013-06-11 6 views
5

Я начал развиваться на Android с последней функцией предоставления услуг: Geofences !! Есть ли известная проблема с провайдером определения местоположения? Следующий пример здесь (https://developer.android.com/training/location/geofencing.html) мой сервис намерений никогда не срабатывал, даже если текущее местоположение находится внутри геозоны. Я использую приложение FakeGPS android как поставщик определения местоположения и, если я имитирую маршрут, я вижу изменения местоположения в приложении «Карты Google», так что агент определения местоположения работает правильно. Есть идеи ?Android geofence с провайдером определения местоположения

Спасибо. Паоло.

ответ

3

Я старался навсегда заставить это работать. Какая боль Google! Так как он говорит, что геофенсионы могут быть легко протестированы с использованием mocks.

Волшебный трюк заключается в использовании имени поставщика «сеть» в местоположении, переданном в setMockLocation.

Location location = new Location("network"); 
    location.setLatitude(latitude); 
    location.setLongitude(longitude); 
    location.setTime(new Date().getTime()); 
    location.setAccuracy(3.0f); 
    location.setElapsedRealtimeNanos(System.nanoTime()); 

    LocationServices.FusedLocationApi.setMockLocation(_googleApiClient, location); 
+2

Дон Вам нужно сначала вызвать LocationServices.FusedLocationApi.setMockMode (_googleApiClient, true)? –

+0

У вас есть ссылка, которая показывает, что LocationServices.GeofencingApi фактически использует LocationServices.FusedLocationApi для насмешки? Я не видел никаких доказательств того, что это правда. – yiati

0

Обязательно включите макет местоположения на телефоне. Выберите «Настройки» -> «Параметры разработчика» -> «Разрешить макет местоположения».

0

LocationServices.FusedLocationApi.setMockMode (GoogleApiClient, правда) должен быть использован перед установкой Mock Местоположение.

1

На самом деле сервис Intent, используемый в приведенном выше примере, хорошо работает, если ваше приложение находится на переднем плане, но когда приложение находится в фоновом режиме, этот IntentService никогда не вызывается. Поэтому нам нужно использовать Broadcast-Receiver вместо службы Intent.

Я нашел этот блог полезным при получении решения.

http://davehiren.blogspot.in/2015/01/android-geofence-stop-getting.html

+0

Ссылка на решение приветствуется, но, пожалуйста, убедитесь, что ваш ответ полезен без него: [добавить контекст вокруг ссылки] (// meta.stackexchange.com/a/8259), чтобы у ваших коллег было некоторое представление о том, что это такое и почему он там, затем укажите наиболее релевантную часть страницы, на которую вы ссылаетесь, в случае недоступности целевой страницы. [Ответы, которые немного больше, чем ссылка, могут быть удалены.] (// stackoverflow.com/help/deleted-answers) –

+0

Хотя эта ссылка может ответить на вопрос, лучше включить здесь основные части ответа и предоставить ссылка для справки. Ответные ссылки могут стать недействительными, если связанная страница изменится. - [Из обзора] (/ review/low-quality-posts/15725231) – Serenity

+0

Вы не должны перекладывать ответ, если до тех пор, пока у вас не будет четкого понимания вопроса и его решения. @Serenity –

1

Вы можете использовать широковещательный приемник вместо активности, как этого

public class GeofenceReceiver extends BroadcastReceiver 
implements 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    ResultCallback<Status>{ 

GoogleApiClient mGoogleApiClient; 
PendingIntent mGeofencePendingIntent ; 
Context mContext; 

@Override 
public void onReceive(Context context, Intent intent) { 
    mContext = context; 
    mGoogleApiClient = new GoogleApiClient.Builder(mContext) 
      .addOnConnectionFailedListener(this) 
      .addConnectionCallbacks(this) 
      .addApi(LocationServices.API) 
      .build(); 

    mGoogleApiClient.connect(); 
} 



@Override 
public void onConnected(@Nullable Bundle bundle) { 
    try { 
     LocationServices.GeofencingApi.addGeofences(
       mGoogleApiClient, 
       // The GeofenceRequest object. 
       getGeofencingRequest(), 
       getGeofencePendingIntent() 
     ).setResultCallback(this); // Result processed in onResult(). 
    } catch (SecurityException securityException) { 
     Log.i(getClass().getSimpleName(),securityException.getMessage()); 
    } 
} 

// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. 
@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

/** 
* Runs when the result of calling addGeofences() and removeGeofences() becomes available. 
* Either method can complete successfully or with an error. 
* 
* Since this activity implements the {@link ResultCallback} interface, we are required to 
* define this method. 
* 
* @param status The Status returned through a PendingIntent when addGeofences() or 
*    removeGeofences() get called. 
*/ 
@Override 
public void onResult(@NonNull Status status) { 
    if (status.isSuccess()) { 
     Log.i(getClass().getSimpleName(),"Success"); 
    } else { 
     // Get the status code for the error and log it using a user-friendly message. 
     Log.i(getClass().getSimpleName(),getErrorString(status.getStatusCode())); 
    } 
} 

private GeofencingRequest getGeofencingRequest() { 
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); 
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL); 
    builder.addGeofences(getGeofecne()); 
    return builder.build(); 
} 

private List<Geofence> getGeofecne(){ 
    List<Geofence> mGeofenceList = new ArrayList<>(); 

    //add one object 
    mGeofenceList.add(new Geofence.Builder() 
      // Set the request ID of the geofence. This is a string to identify this 
      // geofence. 
      .setRequestId("key") 

      // Set the circular region of this geofence. 
      .setCircularRegion(
        25.768466, //lat 
        47.567625, //long 
        50) // radios 

      // Set the expiration duration of the geofence. This geofence gets automatically 
      // removed after this period of time. 
      //1000 millis * 60 sec * 5 min 
      .setExpirationDuration(1000 * 60 * 5) 

      // Set the transition types of interest. Alerts are only generated for these 
      // transition. We track entry and exit transitions in this sample. 
      .setTransitionTypes(
        Geofence.GEOFENCE_TRANSITION_DWELL) 
      //it's must to set time in millis with dwell transition 
      .setLoiteringDelay(3000) 
      // Create the geofence. 
      .build()); 

    return mGeofenceList; 

} 

private PendingIntent getGeofencePendingIntent() { 
    // Reuse the PendingIntent if we already have it. 
    if (mGeofencePendingIntent != null) { 
     return mGeofencePendingIntent; 
    } 
    Intent intent = new Intent(mContext, GeofenceTransitionsIntentService.class); 
    return PendingIntent.getService(mContext, 0, intent, PendingIntent. 
      FLAG_UPDATE_CURRENT); 
} 

}

заканчивал мою репо, есть полный пример использования Geofence https://github.com/3zcs/Geofence

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