这就是我添加地理围栏的方式:

public void setGeofenceRequest(Location location) {
    if (geofences == null) {
        geofences = new ArrayList<Geofence>();
    }
    geofences.add(new Geofence.Builder()
            .setRequestId("3")
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
            .setCircularRegion(
                    location.getLatitude(), location.getLongitude(), PSLocationService.getInstance(context).kPSGeofencingDistanceMedium)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build());
    Intent intent = new Intent(context, ReceiveTransitionsBroadcastReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (geofences.size() > 0) {
        LocationServices.GeofencingApi.addGeofences(mLocationClient, geofences, pi);
        Log.i("", "geof autopilot2 will set geofence for autopilot-3");
    }
}

这是我的广播接收器。我应该在哪里收到它们:
public class ReceiveTransitionsBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context ctx, Intent intent) {
    Log.i("","autopilot valid geof on receive transisionts broadcast receiver");
    PSMotionService.getInstance(ctx).buildGoogleApiClient();
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    int transitionType = geofencingEvent.getGeofenceTransition();
    Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(ctx);
    if(geofencingEvent.getTriggeringLocation() != null) {
        if (geofenceCenter != null) {
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
        } else
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
    }else Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
    if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
        for (Geofence geofence : triggerList) {
            Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
            if(geofence.getRequestId().contentEquals("3")) {
                Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
                Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
                PSLocationService.getInstance(ctx).fastGPS = -1;
                PSLocationService.getInstance(ctx).RequestLocationUpdates();
                if(PSTrip.getActiveTrip() != null) {
                    PSLocationService.getInstance(ctx).removeAutoPilotGeofence();
                }else PSMotionService.getInstance(ctx).checkinTime = System.currentTimeMillis() / 1000;
            }
        }
    }
}
}

现在通常是这样,但并不总是这样。我想说,只有大约75%的时间它应该工作,地理围栏事件实际上被称为。我觉得我设置地理围栏的时间越长,它被调用的可能性就越小。
为什么会这样?当垃圾回收器清理应用程序时,触发事件是否也被解除?
我怎样才能使我的地理围栏总是被调用,当情况?
编辑:
这是我的默认配置:
 defaultConfig {
    minSdkVersion 15
    targetSdkVersion 23

    ndk {
        moduleName "ndkVidyoSample"
    }
}

我从一个广播接收器换成了一个服务:
public class PSGeofenceTransitionsIntentService extends IntentService {
private static ActivityManager manager;
private static PSGeofenceTransitionsIntentService instance;
private GeofencingClient mGeofencingClient;
Context context;
private PendingIntent mGeofencePendingIntent;
public static boolean isMyServiceRunning(Class<?> serviceClass) {
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
public static PSGeofenceTransitionsIntentService getInstance(Context context) {
    if (instance == null) {
        // Create the instance
        instance = new PSGeofenceTransitionsIntentService(context);
    }
    if (!isMyServiceRunning(PSGeofenceTransitionsIntentService.class)) {
        Intent bindIntent = new Intent(context, PSGeofenceTransitionsIntentService.class);
        context.startService(bindIntent);
    }
    // Return the instance
    return instance;
}
public PSGeofenceTransitionsIntentService() {
    super("GeofenceTransitionsIntentService");
}
public PSGeofenceTransitionsIntentService(Context context) {
    super("GeofenceTransitionsIntentService");
    mGeofencingClient = LocationServices.getGeofencingClient(context);
    manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    instance = this;
    this.context = context;
}
protected void onHandleIntent(Intent intent) {
    Log.i("", "autopilot valid geof on receive transisionts broadcast receiver");
    PSMotionService.getInstance(context).buildGoogleApiClient();
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    int transitionType = geofencingEvent.getGeofenceTransition();
    Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(context);
    if (geofencingEvent.getTriggeringLocation() != null) {
        if (geofenceCenter != null) {
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
        } else
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
    } else
        Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
    if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
        for (Geofence geofence : triggerList) {
            Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
            if (geofence.getRequestId().contentEquals("3")) {
                Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
                Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
                PSLocationService.getInstance(context).isLocationRequestsOn = -1;
                PSLocationService.getInstance(context).RequestLocationUpdates();
                if (PSTrip.getActiveTrip() != null) {
                    removeAutoPilotGeofence();
                } else
                    PSMotionService.getInstance(context).checkinTime = System.currentTimeMillis() / 1000;
            }
        }
    }
}
public void removeAutoPilotGeofence() {
    try {
        Log.i("", "autopilot remove autopilot geofence");
        List<String> list = new ArrayList<String>();
        list.add("3");
        if(mGeofencingClient == null)
            mGeofencingClient = LocationServices.getGeofencingClient(context);
        mGeofencingClient.removeGeofences(list).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Utils.appendLog("GEOFENCE removeAutoPilotGeofence Success removing geofences!", "I", Constants.TRACKER);
                Log.i("", "GEOFENCE removeAutoPilotGeofence Success removing geofences!");
                PSApplicationClass.getInstance().pref.setGeoCenterString(context, "-1");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Utils.appendLog("GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage());
            }
        });
        Utils.appendLog("GEOFENCE: Disabling geofence done removeAutoPilotGeofence", "E", Constants.TRACKER);
    } catch (final Exception e) {
        if (e.getMessage().contains("GoogleApiClient") && e.getMessage().contains("not connected")) {
            PSLocationService.getInstance(context).startLocationClient();
            Handler han = new Handler();
            han.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Utils.appendLog("autopilot2 error will try again", "E", Constants.TRACKER);
                    removeAutoPilotGeofence();
                }
            }, 1000);
        }
        Log.i("", "autopilot2 error replaceFragment autopilot geofence:" + e.getMessage());
        Utils.appendLog("autopilot2 error replaceFragment autopilot geofence:" + e.getMessage(), "E", Constants.TRACKER);
    }
}
public void setGeofenceRequest(final Location location) {
    ArrayList geofences = new ArrayList<>();
    geofences.add(new Geofence.Builder()
            .setRequestId("3")
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
            .setCircularRegion(
                    location.getLatitude(), location.getLongitude(), PSLocationService.kPSGeofencingDistanceMedium)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build());
    //ADDING GEOFENCES
    if (geofences.size() > 0) {
        if(mGeofencingClient == null)
            mGeofencingClient = LocationServices.getGeofencingClient(context);
        mGeofencingClient.addGeofences(getGeofencingRequest(location, geofences), getGeofencePendingIntent()).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                RealmLocation realmLocation = new RealmLocation(location.getLatitude(), location.getLongitude(), location.getTime() / 1000, null, true);
                realmLocation.setAccuracy(location.getAccuracy());
                realmLocation.setSpeed(location.getSpeed());
                PSApplicationClass.getInstance().pref.setGeoCenter(realmLocation, context);
                Utils.appendLog("GEOFENCE setGeofenceRequest Success adding geofences!" + location.getLatitude() + " / " + location.getLongitude(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE setGeofenceRequest Success adding geofences! " + location.getLatitude() + " / " + location.getLongitude());
                PSLocationService.getInstance(context).stopLocationClient();
                PSMotionService.getInstance(context).buildGoogleApiClient();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Utils.appendLog("GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage());
            }
        });
        Log.i("", "geof autopilot2 will set geofence for autopilot-3");
    }
}
/**
 * Gets a PendingIntent to send with the request to add or remove 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 getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(context, PSGeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
/**
 * Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored.
 * Also specifies how the geofence notifications are initially triggered.
 */
private GeofencingRequest getGeofencingRequest(Location location, ArrayList<Geofence> geofences) {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
    // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
    // is already inside that geofence.
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
    // Add the geofences to be monitored by geofencing service.
    builder.addGeofences(geofences);
    // Return a GeofencingRequest.
    return builder.build();
}

}
我在其中还有删除和添加地理围栏的代码,监听器总是会在添加它们时进入到一个成功的过程中。

最佳答案

首先,我不会将此代码放入广播接收器中。
除了不好的做法外,组件可能在代码完成执行之前被关闭。
如果需要运行可能需要一些时间的代码,请考虑从接收器启动Service
否则在很短的执行时间内,您可以使用IntentService
通过查看您的代码,我知道您的地理围栏不能按预期工作的两个原因:
1)地理围栏的性质
GeoFencesAPI主要从WiFi/蜂窝数据检索您的位置,而这些数据通常是不可用的。
我曾经试过使用地理围栏,但我发现它们非常不准确。我切换到LocationManager使用纯gps定位,它达到了我的预期。
请参见this answer,它建议
每隔一段时间对GPS硬件进行一次轮询,而不必对结果做任何处理,您将开始获得更精确的地理围栏。
我从未尝试过google的FusedLocation API,但我听到有人说它对他们非常有效。
如果您使用LocationManager,则必须自己实现“地理围栏逻辑”;您可以使用Location.distanceTo(Location)轻松完成此操作。
例子:

final float distanceFromCenter = currentLocation.distanceTo(this.destination);

if (distanceFromCenter <= YOUR_RADIUS_IN_METERS) {
   // you are inside your geofence
}

2)CPU未激活
GeoFences是活动的,这并不一定意味着你的手机是醒着的,正在计算位置检查。
要解决这个问题,您可以从Broacastreceiver启动一个前台服务。服务也应该保持apartial WakeLock
这保证:
操作系统不会终止服务(或者更好:被终止的机会更少…)
用户知道该服务,如有必要可以将其取消
CPU正在运行。因此,您可以确保检索位置的代码正在运行(请记住在服务停止时释放wakelock)。
请注意,如果有必要,android可能仍然会终止您的服务。
你可以在网上找到很多关于如何从广播接收器启动前台服务,如何保持唤醒锁等等的例子…
另外,请查看新的Android O API,它对foregroundservice和其他组件进行了一些小的更改。
PS:我已经开发了使用上述所有组件的应用程序(除了FusedLocation),我非常满意。
编辑:回答OP的问题
好吧,让我们试着在这里订点东西,否则将来的读者很容易迷茫。我将首先回答原始问题和“悬赏横幅”中写的内容,然后回答OP编辑的内容,最后回答OP在评论中提出的问题。
1)原题
当垃圾回收器清理应用程序时,触发事件是否也被解除?
很可能是的。请参阅this answer其中op实现了在单独进程中运行的服务,以便在应用程序被终止时触发geofeen。
如果时间足够长的话,我需要了解是什么导致地理围栏没有被调用
理由很多。看我原来的答案。
我看到GeoFence逻辑的一个实现,它使用的是服务而不是广播接收器,这样会更好吗?
接受者和服务是两码事。请阅读android的文档。您可以从广播接收器启动服务,这通常是“接收”挂起的内容并对其执行操作的首选方式。
2)编辑
请注意,我没有告诉您用服务替换广播接收器,但是从接收器启动服务并处理所有逻辑可能是一个好主意。
使您的intentservice成为singleton类并不必要,因为(从IntentService documentation开始)
所有请求都是在一个工作线程上处理的——它们可能需要尽可能长的时间(并且不会阻塞应用程序的主循环),但一次只处理一个请求。
不要将上下文存储到单例类或某些静态引用中。我很惊讶android工作室没有警告你。
3)评论
我需要这个工作24/7,因此我不能一直使用的位置,因为明显的电池问题。
请阅读Android Oreo Background Execution Limits。这可能是你的问题。
而且,现在我换了一个intentservice,这是否足以确保它保持清醒?
不,就像我说的,你可能需要一个部分唤醒锁来打开CPU。
我需要以另一种方式启动它,以便将它保持在前台吗?
对。要启动前台服务,您需要调用startForeground(int, Notification)
请注意:intentservices的寿命限制在onhandleintent()函数的末尾。一般来说,它们的寿命不应该超过几秒钟。如果要启动前景,请使用服务类。
此外,正如在最初的答案中所说,一个新的前台api是可用的,并且是android oreo的首选。
不是问题,只是一个通知:我需要在这里使用地理围栏。(如有必要,地理围栏将启动GPS
好完美。看看什么最适合你。

关于android - 地理围栏事件并不总是被称为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46450225/

10-10 17:07