簡體   English   中英

Android地理圍欄與模擬位置提供商

[英]Android geofence with mock location provider

我已經開始在Android上開發具有最后定位服務功能:Geofences !! 模擬位置提供程序有任何已知問題嗎? 以下示例( https://developer.android.com/training/location/geofencing.html )即使當前位置在地理圍欄內,我的意圖服務也從未被解雇。 我正在使用FakeGPS Android應用程序作為模擬位置提供商,如果我模擬路線,我會在Google地圖應用上看到位置更改,因此模擬位置提供商運行良好。 有任何想法嗎 ?

謝謝。 保羅。

我一直試着讓它發揮作用。 多么痛苦谷歌! 因為它說地理圍欄可以很容易地使用模擬進行測試。

神奇的技巧是在傳遞給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);

實際上,如果您的應用程序位於前台,但在應用程序處於后台時,上述示例中使用的Intent服務效果很好,但此IntentService永遠不會被調用。所以我們需要使用Broadcast-Receiver而不是Intent服務。

我發現這個博客有助於獲得解決方案。

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

你可以使用廣播接收器而不是像這樣的活動

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

}

看看我的回購,有一個使用地理圍欄的完整示例https://github.com/3zcs/Geofence

確保在手機上啟用模擬位置。 選擇設置 - >開發者選項 - >“允許模擬位置”。

Geofences使用FusedLocationProviderApi來模擬它們你必須使用FusedLocationProviderApi.setMockLocation

在設置模擬位置之前,需要使用LocationServices.FusedLocationApi.setMockMode(googleApiClient,true)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM