2014-10-29 28 views
14

Birisi LocationServices.GeofencingApi kullanarak örnek biliyor mu? Bulduğum tüm android geofencing örnekleri, kullanımdan kaldırılmış LocationClient sınıfını kullanıyor. Gördüğüm kadarıyla, LocationServices sınıfı kullanılabilecek olandan, ancak nasıl kullanılacağı konusunda herhangi bir çalışma örneği yok gibi görünüyor. Bulduğum en yakın cevabı this git example projedir - ama hala tetiklenen çitler olsun kaldırılmış LocationClient kullanır:Android LocationServices.GeofencingApi örnek kullanımı

buldum en yakın konum güncellemesini vurgulayarak this sonrası

GÜNCELLEME istekleri olduğunu.

+0

Eğer kaynağında çalıştı yaptı: Belirli bağlantı burada http CaMg – Selvin

+2

http://d.android.com makale başlığının eğitim bölümü kısaltması olan: // Kullanımdan kaldırılan LocationClient sınıfını kullanan developer.android.com/training/location/geofencing.html - dokümanları güncellemedikleri görünüyor mu? – InquisitorJax

cevap

26

Kodumu yeni API'ye geçirdim.

bu Yanıta göre GitHub üzerinde bir çalışma projesi: https://github.com/androidfu/GeofenceExample

Bu yardımcı sınıfı API kullanarak coğrafi çitler kaydeder Burada çalışan bir örnektir. Çağrı aktivitesi/parçası ile iletişim kurmak için bir geri arama arayüzü kullanıyorum. İhtiyaçlarınıza uygun bir geri bildirim oluşturabilirsiniz.

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

Bu sınıf coğrafi bölge geçiş alıcı için temel sınıftır.

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

Bu sınıf soyut sınıf uygulayan ve Geofence geçişler

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

Ve Manifest'inizde eklenti içinde tüm işlenmesini yapar:

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

Geri arama arabirimi

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

    public void onGeofencesRegisteredSuccessful(); 
} 
+0

geri bildirimi de sağlayabilir miydiniz? Ben android geliştirme için yeni, kodunuzu paylaşırsanız güzel olurdu :) thx – BastianW

+0

@BastianW emin, kod eklendi :) – L93

+6

Dokümanlar göre, '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, Liste , PendingIntent); '' 'de, kullanımdan kaldırılmıştır. '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, GeofencingRequest, PendingIntent);' 'yerine,' '' GeofencingRequest''' ilkini oluşturarak '' 'GeofencingRequest geofenceRequest = new GeofencingRequest.Builder(). AddGeofences (mGeofencesToAdd)) .build(); '' – Ruben