2014-10-29 12 views
14

Czy ktoś wie o przykładzie użycia LocationServices.GeofencingApi? Wszystkie znalezione przeze mnie przykłady geofence w systemie Android używają wycofanej klasy LocationClient. Z tego co widzę, klasa LocationServices jest tą, której należy użyć, ale nie ma żadnych działających przykładów na jej użycie.Android LocationServices.GeofencingApi przykład użycia

Najbliższy znalazłem jest this po podkreślając aktualizacji lokalizacji żąda

UPDATE: Najbliżej odpowiedź znalazłem jest this git example projekt - ale nadal korzysta z przestarzałej LocationClient dostać wyzwalanych ogrodzeń.

+0

nie próbowałeś u źródła: http://d.android.com w sekcji szkolenia akronim tytuł artykułu jest CaMg – Selvin

+2

Specyficzny link jest tutaj http: // developer.android.com/training/location/geofencing.html , która używa przestarzałej klasy LocationClient - wygląda na to, że nie zaktualizowała jeszcze dokumentacji – InquisitorJax

Odpowiedz

26

Właśnie zmigrowałem mój kod do nowego API. Oto przykład roboczych:

projekt roboczy na GitHub na podstawie tej odpowiedzi: https://github.com/androidfu/GeofenceExample

Ta klasa pomocnika rejestruje granic geograficznych za pomocą interfejsu API. Używam interfejsu wywołania zwrotnego do komunikacji z działaniem/fragmentem wywołującym. Możesz zbudować callback, który pasuje do twoich potrzeb.

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

Ta klasa jest klasą bazową dla Geofence odbiornika przejściowego.

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

Ta klasa implementuje klasę abstrakcyjną i wykonuje całą obsługę przejściami 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); 
    } 
} 

iw swoim oczywistym dodają:

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

Interfejs telefoniczny

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

    public void onGeofencesRegisteredSuccessful(); 
} 
+0

czy mógłbyś podać również swój callback? Jestem nowy w rozwoju Androida, byłoby miło, gdybyś mógł podzielić się swoim kodem :) thx – BastianW

+0

@BastianW pewnie, kod dodany :) – L93

+6

Według dokumentów, metoda "' LocationServices.GeofencingApi.addGeofences (GoogleApiClient, List , PendingIntent), '' 'jest również przestarzałe. Użyj opcji '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, GeofencingRequest, PendingIntent),' '' zamiast tego, tworząc najpierw '' 'GeofencingRequest''': GeofencingRequest = new GeofencingRequest.Builder() .GogofencingToAdd) .build(); '' ' – Ruben

Powiązane problemy