2014-10-29 2 views
14

누구나 LocationServices.GeofencingApi를 사용하는 예를 알고 있습니까? 내가 발견 한 모든 안드로이드 지오 코딩 예제는 사용되지 않는 LocationClient 클래스를 사용하고 있습니다. 내가 볼 수 있듯이 LocationServices 클래스가 사용되지만 사용 방법에 대한 예제가없는 것처럼 보입니다. 내가 찾은 가장 가까운 답은 this git example 프로젝트 -하지만 여전히 트리거 울타리를 얻기 위해 사용되지 LocationClient을 사용Android LocationServices.GeofencingApi 예제 사용

내가 찾은 가장 가까운 위치 갱신을 강조 this 게시물

UPDATE를 요청합니다.

+0

당신이 소스에서 시도했다 : 특정 링크가 여기에 HTTP입니다 CaMG – Selvin

+2

http://d.android.com 기사 제목의 교육 섹션 약어에서입니다 : // developer.android.com/training/location/geofencing.html Deprecated LocationClient 클래스를 사용하는 - 문서를 아직 업데이트하지 않은 것 같습니다 – InquisitorJax

답변

26

방금 ​​내 코드를 새 API로 마이그레이션했습니다.

이 답변에 따라 GitHub의에 작업 프로젝트 : https://github.com/androidfu/GeofenceExample

이 헬퍼 클래스는 API를 사용하여 지오 펜스를 등록 다음은 작업 예입니다. callback 인터페이스를 사용하여 호출하는 activity/fragment와 통신합니다. 필요에 맞는 콜백을 만들 수 있습니다.

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

이 클래스는 지오 펜스 전환 수신기의 기본 클래스입니다.

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

이 클래스는 추상 클래스를 구현하고 지오 펜스 전환

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

그리고 매니페스트 추가에서의 모든 처리 수행합니다

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

콜백 인터페이스

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

    public void onGeofencesRegisteredSuccessful(); 
} 
+0

콜백도 제공 할 수 있습니까? 나는 당신의 코드를 공유 할 수 있다면 좋을 것이다. :) thx – BastianW

+0

@BastianW 틀림 : 코드가 추가됨 :) – L93

+6

문서에 따르면,''LocationServices.GeofencingApi.addGeofences (GoogleApiClient, List , PendingIntent);''도 사용되지 않습니다. GeofencingRequest.Builder()를 추가하여 LocationServices.GeofencingApi.addGeofences (GoogleApiClient, GeofencingRequest, PendingIntent);''를 사용하십시오. addGeofences (mGeofencesToAdd) .build();''' – Ruben