2013-06-11 15 views
5

Ho iniziato a sviluppare su Android con l'ultima funzione di servizi di localizzazione: Geofences !! C'è qualche problema noto con il fornitore di localizzazione fittizio? Seguendo l'esempio qui (https://developer.android.com/training/location/geofencing.html) il mio servizio di intent non è mai stato attivato anche se la posizione corrente è all'interno del geofence. Sto usando l'app Android FakeGPS come fornitore di postazioni fittizie e, se simulo un percorso, vedo le modifiche alla posizione sull'app Google Maps, quindi il fornitore di postazioni fittizie sta funzionando bene. Qualche idea ?Geofence Android con fornitore di postazioni fittizie

Grazie. Paolo.

risposta

3

Ho provato per sempre a farlo funzionare. Che dolore Google! Dal momento che dice che i geofences possono essere facilmente testati usando le finte.

Il trucco magico consiste nell'utilizzare il nome del provider "rete" nella Posizione passata a 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

Don devi prima chiamare LocationServices.FusedLocationApi.setMockMode (_googleApiClient, true) prima? –

+0

Hai un link che mostra che LocationServices.GeofencingApi utilizza effettivamente LocationServices.FusedLocationApi per il mocking? Non ho visto alcuna prova che sia vero. – yiati

0

Assicurarsi di abilitare posizioni fittizie sul telefono. Seleziona Impostazioni-> Opzioni sviluppatore -> "Consenti posizioni simulate".

0

LocationServices.FusedLocationApi.setMockMode (googleApiClient, true) deve essere utilizzato prima di impostare Mock Posizione.

1

In realtà il servizio utilizzato nell'esempio menzionato funziona correttamente se la tua app è in primo piano ma quando l'app è in background, questo IntentService non viene mai chiamato. Quindi dobbiamo utilizzare Broadcast-Receiver anziché il servizio Intent.

Ho trovato questo blog utile per ottenere una soluzione.

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

+0

Un collegamento a una soluzione è il benvenuto, ma per favore assicurati che la tua risposta sia utile senza di essa: [aggiungi contesto intorno al link] (// meta.stackexchange.com/a/8259) in modo che i tuoi utenti abbiano qualche idea di cosa sia e perché è lì, quindi cita la parte più pertinente della pagina a cui stai collegando nel caso in cui la pagina di destinazione non sia disponibile. [Le risposte che sono poco più di un collegamento possono essere eliminate.] (// stackoverflow.com/help/deleted-answers) –

+0

Sebbene questo collegamento possa rispondere alla domanda, è meglio includere qui le parti essenziali della risposta e fornire il link per riferimento. Le risposte di solo collegamento possono diventare non valide se la pagina collegata cambia. - [Dalla revisione] (/ recensione/post di bassa qualità/15725231) – Serenity

+0

Non si dovrebbe procedere a un Downvote della risposta a meno che, fino a quando, non si abbia una chiara comprensione della domanda e della sua soluzione. @Serenity –

1

È possibile utilizzare il ricevitore di broadcast invece di un'attività come questa

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); 
} 

}

controllare il mio repo, c'è un esempio completo di utilizzo di geofence https://github.com/3zcs/Geofence

Problemi correlati