Android地理围栏与模拟位置提供商

时间:2013-06-11 16:16:41

标签: android android-location android-geofence

我已开始在Android上开发具有最后定位服务功能:Geofences !!模拟位置提供程序有任何已知问题吗?以下示例(https://developer.android.com/training/location/geofencing.html)即使当前位置在地理围栏内,我的意图服务也从未被解雇。我正在使用FakeGPS Android应用程序作为模拟位置提供商,如果我模拟路线,我会在Google地图应用上看到位置更改,因此模拟位置提供商运行良好。有什么想法吗?

感谢。 保罗。

6 个答案:

答案 0 :(得分:3)

我一直试着让它发挥作用。多么痛苦谷歌!因为它说地理围栏很容易使用模拟进行测试。

神奇的诀窍是在传递给setMockLocation的位置使用提供者名称“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);

答案 1 :(得分:1)

实际上,如果您的应用程序位于前台,但是当应用程序处于后台时,上述示例中使用的Intent服务效果很好,但从未调用此IntentService。因此我们需要使用Broadcast-Receiver而不是Intent服务。

我发现这个博客对获得解决方案很有帮助。

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

答案 2 :(得分: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);
}

}

查看我的回购,有一个使用地理围栏的完整示例 https://github.com/3zcs/Geofence

答案 3 :(得分:0)

确保在手机上启用模拟位置。选择设置 - >开发者选项 - &gt;&#34;允许模拟位置&#34;。

答案 4 :(得分:0)

Geofences使用FusedLocationProviderApi来模拟它们你必须使用FusedLocationProviderApi.setMockLocation

答案 5 :(得分:0)

LocationServices.FusedLocationApi.setMockMode(googleApiClient,true) 需要在设置Mock Location之前使用。