2014-10-29 10 views
14

Qualcuno sa di un esempio di utilizzo di LocationServices.GeofencingApi? Tutti gli esempi di geofencing android che trovo utilizzano la classe LocationClient deprecata. Da quello che posso vedere, la classe LocationServices è quella da usare, ma non sembrano esserci esempi funzionanti su come usarlo.LocationServices Android.GeofencingApi esempio di utilizzo

Il più vicino che ho trovato è this messaggio evidenziando aggiornamento della posizione richiede

UPDATE: La risposta più vicina che ho trovato è this git example progetto - ma utilizza ancora il LocationClient deprecato per ottenere recinzioni innescati.

+0

hai provato alla fonte: http://d.android.com alla sezione di formazione acronimo di titolo dell'articolo è CaMg – Selvin

+2

Il legame specifico è qui http: // developer.android.com/training/location/geofencing.html che utilizza la classe LocationClient deprecata - sembra che non abbiano ancora aggiornato la documentazione – InquisitorJax

risposta

26

Ho appena migrato il mio codice alla nuova API. Ecco un esempio di lavoro:

Un progetto di lavoro su GitHub in base a questa risposta: https://github.com/androidfu/GeofenceExample

Questa classe di supporto registra i geofences utilizzando l'API. Uso un'interfaccia di callback per comunicare con l'attività/frammento di chiamata. È possibile creare una richiamata adatta alle proprie esigenze.

public class GeofencingRegisterer implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 
    private Context mContext; 
    private GoogleApiClient mGoogleApiClient; 
    private List<Geofence> geofencesToAdd; 
    private PendingIntent mGeofencePendingIntent; 

    private GeofencingRegistererCallbacks mCallback; 

    public final String TAG = this.getClass().getName(); 

    public GeofencingRegisterer(Context context){ 
     mContext =context; 
    } 

    public void setGeofencingCallback(GeofencingRegistererCallbacks callback){ 
     mCallback = callback; 
    } 

    public void registerGeofences(List<Geofence> geofences){ 
     geofencesToAdd = geofences; 

     mGoogleApiClient = new GoogleApiClient.Builder(mContext) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 


    @Override 
    public void onConnected(Bundle bundle) { 
     if(mCallback != null){ 
      mCallback.onApiClientConnected(); 
     } 

     mGeofencePendingIntent = createRequestPendingIntent(); 
     PendingResult<Status> result = LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, geofencesToAdd, mGeofencePendingIntent); 
     result.setResultCallback(new ResultCallback<Status>() { 
      @Override 
      public void onResult(Status status) { 
       if (status.isSuccess()) { 
        // Successfully registered 
        if(mCallback != null){ 
         mCallback.onGeofencesRegisteredSuccessful(); 
        } 
       } else if (status.hasResolution()) { 
        // Google provides a way to fix the issue 
        /* 
        status.startResolutionForResult(
          mContext,  // your current activity used to receive the result 
          RESULT_CODE); // the result code you'll look for in your 
        // onActivityResult method to retry registering 
        */ 
       } else { 
        // No recovery. Weep softly or inform the user. 
        Log.e(TAG, "Registering failed: " + status.getStatusMessage()); 
       } 
      } 
     }); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     if(mCallback != null){ 
      mCallback.onApiClientSuspended(); 
     } 

     Log.e(TAG, "onConnectionSuspended: " + i); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     if(mCallback != null){ 
      mCallback.onApiClientConnectionFailed(connectionResult); 
     } 

     Log.e(TAG, "onConnectionFailed: " + connectionResult.getErrorCode()); 
    } 



    /** 
    * Returns the current PendingIntent to the caller. 
    * 
    * @return The PendingIntent used to create the current set of geofences 
    */ 
    public PendingIntent getRequestPendingIntent() { 
     return createRequestPendingIntent(); 
    } 

    /** 
    * Get a PendingIntent to send with the request to add Geofences. Location 
    * Services issues the Intent inside this PendingIntent whenever a geofence 
    * transition occurs for the current list of geofences. 
    * 
    * @return A PendingIntent for the IntentService that handles geofence 
    * transitions. 
    */ 
    private PendingIntent createRequestPendingIntent() { 
     if (mGeofencePendingIntent != null) { 
      return mGeofencePendingIntent; 
     } else { 
      Intent intent = new Intent(mContext, GeofencingReceiver.class); 
      return PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
     } 
    } 
} 

Questa classe è la classe base per il ricevitore di transizione geofence.

public abstract class ReceiveGeofenceTransitionIntentService extends IntentService { 

    /** 
    * Sets an identifier for this class' background thread 
    */ 
    public ReceiveGeofenceTransitionIntentService() { 
     super("ReceiveGeofenceTransitionIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     GeofencingEvent event = GeofencingEvent.fromIntent(intent); 
     if(event != null){ 

      if(event.hasError()){ 
       onError(event.getErrorCode()); 
      } else { 
       int transition = event.getGeofenceTransition(); 
       if(transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_DWELL || transition == Geofence.GEOFENCE_TRANSITION_EXIT){ 
        String[] geofenceIds = new String[event.getTriggeringGeofences().size()]; 
        for (int index = 0; index < event.getTriggeringGeofences().size(); index++) { 
         geofenceIds[index] = event.getTriggeringGeofences().get(index).getRequestId(); 
        } 

        if (transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_DWELL) { 
         onEnteredGeofences(geofenceIds); 
        } else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) { 
         onExitedGeofences(geofenceIds); 
        } 
       } 
      } 

     } 
    } 

    protected abstract void onEnteredGeofences(String[] geofenceIds); 

    protected abstract void onExitedGeofences(String[] geofenceIds); 

    protected abstract void onError(int errorCode); 
} 

Questa classe implementa la classe astratta e fa tutto la gestione delle transizioni geofence

public class GeofencingReceiver extends ReceiveGeofenceTransitionIntentService { 

    @Override 
    protected void onEnteredGeofences(String[] geofenceIds) { 
     Log.d(GeofencingReceiver.class.getName(), "onEnter"); 
    } 

    @Override 
    protected void onExitedGeofences(String[] geofenceIds) { 
     Log.d(GeofencingReceiver.class.getName(), "onExit"); 
    } 

    @Override 
    protected void onError(int errorCode) { 
     Log.e(GeofencingReceiver.class.getName(), "Error: " + i); 
    } 
} 

E nel manifesto aggiuntivo:

<service 
     android:name="**xxxxxxx**.GeofencingReceiver" 
     android:exported="true" 
     android:label="@string/app_name" > 
</service> 

interfaccia di callback

public interface GeofencingRegistererCallbacks { 
    public void onApiClientConnected(); 
    public void onApiClientSuspended(); 
    public void onApiClientConnectionFailed(ConnectionResult connectionResult); 

    public void onGeofencesRegisteredSuccessful(); 
} 
+0

potresti fornire anche il callback? Sono nuovo allo sviluppo di Android, sarebbe bello se potessi condividere il tuo codice :) thx – BastianW

+0

@BastianW sicuro, codice aggiunto :) – L93

+6

Secondo i documenti, il metodo '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, List , PendingIntent); anche '' 'è deprecato. Usa '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, GeofencingRequest, PendingIntent);' '' invece, creando prima un '' 'GeofencingRequest''':' '' GeofencingRequest geofenceRequest = new GeofencingRequest.Builder(). AddGeofences (mGeofencesToAdd) .build(); '' ' – Ruben

Problemi correlati