2014-10-29 20 views
14

Có ai biết ví dụ về việc sử dụng LocationServices.GeofencingApi không? Tất cả các ví dụ về định vị địa lý trên Android mà tôi thấy đều sử dụng lớp LocationClient không được chấp nhận. Từ những gì tôi có thể thấy, lớp LocationServices là một lớp để sử dụng, nhưng dường như không có bất kỳ ví dụ làm việc nào về cách sử dụng nó.Android LocationServices.GeofencingApi sử dụng ví dụ

Gần nhất tôi đã tìm thấy là this bài nổi bật cập nhật vị trí yêu cầu

UPDATE: Câu trả lời gần nhất tôi đã tìm thấy là this git example dự án - nhưng nó vẫn sử dụng LocationClient bị phản đối để có được hàng rào kích hoạt.

+0

bạn đã cố gắng tại nguồn: http://d.android.com ở phần đào tạo từ viết tắt của tiêu đề bài viết là CaMG – Selvin

+2

Các liên kết cụ thể là ở đây http: // developer.android.com/training/location/geofencing.html sử dụng lớp LocationClient không được chấp nhận - có vẻ như họ chưa cập nhật tài liệu chưa – InquisitorJax

Trả lời

26

Tôi vừa di chuyển mã của mình sang API mới. Dưới đây là một ví dụ làm việc:

Một dự án làm việc trên GitHub dựa trên câu trả lời này: https://github.com/androidfu/GeofenceExample

lớp helper này đăng ký các giới hạn địa lý bằng cách sử dụng API. Tôi sử dụng giao diện gọi lại để liên lạc với hoạt động/đoạn gọi. Bạn có thể xây dựng một cuộc gọi lại phù hợp với nhu cầu của bạn.

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

Lớp này là lớp cơ sở cho nhận chuyển geofence của bạn.

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

Lớp này thực hiện các lớp trừu tượng và làm tất cả việc xử lý các hiệu ứng chuyển tiếp 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); 
    } 
} 

Và trong add biểu hiện của bạn:

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

Interface Callback

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

    public void onGeofencesRegisteredSuccessful(); 
} 
+0

bạn cũng có thể cung cấp gọi lại không? Tôi mới phát triển Android, sẽ là tốt đẹp nếu bạn có thể chia sẻ mã của bạn :) thx – BastianW

+0

@BastianW chắc chắn, mã được thêm :) – L93

+6

Theo tài liệu, phương pháp '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, List , PendingIntent); '' 'cũng không được dùng nữa. Sử dụng '' 'LocationServices.GeofencingApi.addGeofences (GoogleApiClient, GeofencingRequest, PendingIntent);' '' thay vào đó, bằng cách tạo '' 'GeofencingRequest''' trước:' '' GeofencingRequest geofenceRequest = new GeofencingRequest.Builder(). AddGeofences (mGeofencesToAdd) .build(); '' ' – Ruben