2013-06-11 2 views
5

지난 위치 서비스 기능을 갖춘 Android에서 개발을 시작했습니다 : Geofences !! 모의 위치 정보 제공자에게 알려진 문제점이 있습니까? 다음 예 (https://developer.android.com/training/location/geofencing.html)에 따라 현재 위치가 지오 펜스 내부에 있더라도 내 인 텐트 서비스가 실행되지 않습니다. Mock 위치 제공 업체로 FakeGPS android app을 사용하고 있습니다. 경로를 시뮬레이트하면 Google Maps 앱에서 위치가 변경된 것을 볼 수 있으므로 모의 위치 제공 업체가 잘 작동합니다. 어떤 아이디어?모의 위치 정보 제공자가있는 Android 지오 펜스

감사합니다. 파올로.

답변

3

나는 이것을 영원히 작동 시키려고 노력했다. 이 얼마나 고통스러운 구글! 지오 펜스 (geofences)는 모의를 사용하여 쉽게 테스트 할 수 있다고 말합니다.

마법의 트릭은 setMockLocation에 전달 된 Location에서 제공자 이름 "network"를 사용하는 것입니다.

Location location = new Location("network"); 
    location.setLatitude(latitude); 
    location.setLongitude(longitude); 
    location.setTime(new Date().getTime()); 
    location.setAccuracy(3.0f); 
    location.setElapsedRealtimeNanos(System.nanoTime()); 

    LocationServices.FusedLocationApi.setMockLocation(_googleApiClient, location); 
+2

돈 지오 펜스 를 사용하는 전체 예제가있다 먼저 LocationServices.FusedLocationApi.setMockMode (_googleApiClient, true)를 호출해야합니까? –

+0

LocationServices.GeofencingApi가 조롱을 위해 실제로 LocationServices.FusedLocationApi를 사용한다는 것을 보여주는 링크가 있습니까? 나는 그것이 사실이라는 어떠한 증거도 보지 못했다. – yiati

0

휴대 전화에서 모의 ​​위치를 ​​사용해야합니다. 설정 -> 개발자 옵션 -> "모의 위치 허용"을 선택하십시오.

0

LocationServices.FusedLocationApi.setMockMode (googleApiClient, true)를 사용할 필요가 그래서 그들을 조롱 FusedLocationProviderApi를 사용합니다.

1

실제로 의도 한 예에서 사용 된 의도 서비스는 앱이 포 그라운드에 있지만 앱이 백그라운드에있는 경우에 효과적입니다.이 IntentService는 호출되지 않습니다. 인 텐트 서비스 대신 브로드 캐스트 수신기를 사용해야합니다.

이 블로그는 솔루션을 얻는 데 도움이되는 것으로 나타났습니다.

http://davehiren.blogspot.in/2015/01/android-geofence-stop-getting.html

+0

솔루션에 대한 링크는 환영하지만, 답변이 없으면 대답이 유용하다는 점을 명심하십시오. [링크 주변 환경 추가] (// meta.stackexchange.com/a/8259) 동료 사용자가 자신의 의견을 파악할 수 있도록하십시오. 그리고 왜 그곳에 있는지, 그리고 목표 페이지를 사용할 수 없을 때 당신이 링크하고있는 페이지의 가장 중요한 부분을 인용하십시오. [링크보다 조금 더 많은 대답은 삭제 될 수 있습니다.] (// stackoverflow.com/help/deleted-answers) –

+0

이 링크가 질문에 대답 할 수 있지만 여기에 답변의 핵심 부분을 포함시키고 참조 용 링크. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [리뷰에서] (리뷰/저품절 포스트/15725231) – Serenity

+0

질문과 해결책에 대한 명확한 이해가 끝날 때까지 답을 다운 그레이드해서는 안됩니다. @Serenity –

1

당신이

public class GeofenceReceiver extends BroadcastReceiver 
implements 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    ResultCallback<Status>{ 

GoogleApiClient mGoogleApiClient; 
PendingIntent mGeofencePendingIntent ; 
Context mContext; 

@Override 
public void onReceive(Context context, Intent intent) { 
    mContext = context; 
    mGoogleApiClient = new GoogleApiClient.Builder(mContext) 
      .addOnConnectionFailedListener(this) 
      .addConnectionCallbacks(this) 
      .addApi(LocationServices.API) 
      .build(); 

    mGoogleApiClient.connect(); 
} 



@Override 
public void onConnected(@Nullable Bundle bundle) { 
    try { 
     LocationServices.GeofencingApi.addGeofences(
       mGoogleApiClient, 
       // The GeofenceRequest object. 
       getGeofencingRequest(), 
       getGeofencePendingIntent() 
     ).setResultCallback(this); // Result processed in onResult(). 
    } catch (SecurityException securityException) { 
     Log.i(getClass().getSimpleName(),securityException.getMessage()); 
    } 
} 

// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. 
@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

/** 
* Runs when the result of calling addGeofences() and removeGeofences() becomes available. 
* Either method can complete successfully or with an error. 
* 
* Since this activity implements the {@link ResultCallback} interface, we are required to 
* define this method. 
* 
* @param status The Status returned through a PendingIntent when addGeofences() or 
*    removeGeofences() get called. 
*/ 
@Override 
public void onResult(@NonNull Status status) { 
    if (status.isSuccess()) { 
     Log.i(getClass().getSimpleName(),"Success"); 
    } else { 
     // Get the status code for the error and log it using a user-friendly message. 
     Log.i(getClass().getSimpleName(),getErrorString(status.getStatusCode())); 
    } 
} 

private GeofencingRequest getGeofencingRequest() { 
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); 
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL); 
    builder.addGeofences(getGeofecne()); 
    return builder.build(); 
} 

private List<Geofence> getGeofecne(){ 
    List<Geofence> mGeofenceList = new ArrayList<>(); 

    //add one object 
    mGeofenceList.add(new Geofence.Builder() 
      // Set the request ID of the geofence. This is a string to identify this 
      // geofence. 
      .setRequestId("key") 

      // Set the circular region of this geofence. 
      .setCircularRegion(
        25.768466, //lat 
        47.567625, //long 
        50) // radios 

      // Set the expiration duration of the geofence. This geofence gets automatically 
      // removed after this period of time. 
      //1000 millis * 60 sec * 5 min 
      .setExpirationDuration(1000 * 60 * 5) 

      // Set the transition types of interest. Alerts are only generated for these 
      // transition. We track entry and exit transitions in this sample. 
      .setTransitionTypes(
        Geofence.GEOFENCE_TRANSITION_DWELL) 
      //it's must to set time in millis with dwell transition 
      .setLoiteringDelay(3000) 
      // Create the geofence. 
      .build()); 

    return mGeofenceList; 

} 

private PendingIntent getGeofencePendingIntent() { 
    // Reuse the PendingIntent if we already have it. 
    if (mGeofencePendingIntent != null) { 
     return mGeofencePendingIntent; 
    } 
    Intent intent = new Intent(mContext, GeofenceTransitionsIntentService.class); 
    return PendingIntent.getService(mContext, 0, intent, PendingIntent. 
      FLAG_UPDATE_CURRENT); 
} 

}

체크 아웃 내 REPO처럼 대신 활동의 방송 수신기를 사용할 수 https://github.com/3zcs/Geofence

관련 문제