地理围栏事件并不总是被称为 [英] Geofence events not always called

查看:104
本文介绍了地理围栏事件并不总是被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的BroadcastReceiver.我应该在哪里收到它们:

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:

 defaultConfig {
    minSdkVersion 15
    targetSdkVersion 23

    ndk {
        moduleName "ndkVidyoSample"
    }
}

我从广播接收器更改为IntentService:

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

}

我也有删除和添加地理围栏的代码,并且侦听器总是在添加它们时进入onSuccess.

解决方案

对于初学者来说,我不会将此代码放入BroadcastReceiver中.

除了不好的做法外,还可能在代码执行完毕之前关闭组件.

如果需要运行,请考虑从接收器启动服务代码可能需要一些时间. 否则,在较短的执行时间内,您可以使用 IntentService .

通过查看您的代码,我知道您的地理围栏无法按预期工作的两个原因:

1)地理围栏的性质

Geofences API主要从WiFi/蜂窝数据(通常不可用)中检索您的位置.

我曾经尝试使用地理围栏,但发现它们非常不准确.我切换到 LocationManager ,使其使用纯GPS定位并且符合我的期望

请参见此答案,建议您

不定期对GPS硬件进行轮询而不会对其进行任何处理,您将开始获得更准确的地理围栏.

我从未尝试过Google的 FusedLocation API ,但我听说有人说它对他们非常有效.

如果您使用LocationManager,则必须自己实现地理围栏逻辑";您可以使用 Location.distanceTo(位置).

示例:

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

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

2)CPU处于不活动状态

地理围栏处于活动状态这一事实并不一定意味着您的电话处于唤醒状态并正在计算位置检查.

要解决此问题,可以从BroacastReceiver启动ForegroundService.服务还应包含部分WakeLock . 这样可以保证:

  1. 操作系统不会终止该服务(或更有效:被终止的机会更少...)
  2. 用户了解该服务,并可以在必要时将其关闭
  3. CPU正在运行.因此,您可以确保检索位置的代码正在运行(请记住在服务停止时释放WakeLock).

请注意,如果有必要,Android可能仍会终止您的服务.

您可以在网上找到许多示例,这些示例涉及如何从BroadcastReceiver启动ForegroundService,如何持有WakeLock等...

另外,请查看新的 Android O API ,对ForegroundService和其他组件进行了一些小的更改.

PS:我开发并使用了上面提到的所有组件(FusedLocation除外)的应用程序,对此感到非常满意.

回答OP的问题

Okey,让我们尝试在此处进行一些订购,否则将来的读者可能会很容易感到困惑.首先,我将回答原始问题和赏金标语"中写的内容,然后编辑OP,最后是OP放置在评论中的问题.

1)原始问题

当应用程序被垃圾收集器清理时,触发事件是否也被取消?

大概是.请参阅此答案,其中OP实施了在单独的进程中运行的服务,即使在应用程序运行时也可以触发地理围栏被杀死.

如果时间已经过去,我需要了解是什么原因导致地理围栏不被调用

很多原因.看看我原来的答案.

我看到了用服务而不是广播接收器实现地理围栏逻辑的实现,这样会更好吗?

接收者和服务是两个不同的事物.请阅读Android文档.您可以从BroadcastReceiver启动服务,这通常是接收" PendingIntent并对其执行操作的首选方式.

2)修改

  • 请注意,我没有告诉您用服务替换BroadcastReceiver,但是从接收器启动服务并在那里处理所有逻辑可能是个好主意.
  • 不必为您的IntentService创建Singleton类,因为(来自 IntentService文档)

所有请求都在单个工作线程上处理-它们可能会花费必要的时间(并且不会阻塞应用程序的主循环),但是一次只会处理一个请求.

  • 请勿将Context存储到Singleton类或某些静态引用中.我印象深刻,Android Studio并未警告您.

3)评论

我需要此功能才能24/7正常工作,因此,由于电池问题明显,我无法一直使用该位置.

请阅读 Android Oreo背景执行限制.这可能对您来说是个问题.

现在我更改为intentService了,是否足以确保它保持清醒状态?

不,正如我所说,您可能需要部分WakeLock才能打开CPU.

我是否需要以其他方式启动它,以使其处于前台?

是的.为了启动前景服务,您需要调用 startForeground(int,Notification)

请注意:IntentServices的生命周期仅限于onHandleIntent()函数的结尾.通常,他们的寿命不应超过几秒钟.如果要启动前台,请使用Service类.

此外,正如原始答案中所述,新的Foreground API已推出,并且是Android Oreo的首选.

不是问题,只是通知:我需要在此处使用地理围栏. (如果需要,地理定位将开始

好的.看看最适合您的东西.

This is how I add my geofences:

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

And this is my BroadcastReceiver. Where I should receive them:

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

Now usually it works, but not always. I would say that only about 75% of the time it should work, the geofence events are actually called. I feel like the more time since I've set the geofence, the less likely it will be to be called. Why is this happening? Is the triggering event also being dismissed, when the app is cleaned by the garbage collector? How can I make it so that my geofence is always being called, when the case?

EDIT:

This is my defaultConfig:

 defaultConfig {
    minSdkVersion 15
    targetSdkVersion 23

    ndk {
        moduleName "ndkVidyoSample"
    }
}

I changed from a Broadcast Receiver to a IntentService:

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

}

I have in it also the code to remove and add the geofences, and the listener always goes into onSuccess regarding adding them.

解决方案

For starters, I would not put this code inside a BroadcastReceiver.

Besides being bad practice, the component might be shutdown before the code has finished executing.

Please consider starting a Service from your Receiver, if you need to run code that might take some time. Otherwise for a short execution time, you may use an IntentService.

By looking at your code, I'm aware of two reasons your Geofences are not working as expected:

1) The nature of Geofences

Geofences API retrieves your location mostly from WiFi / Cellular Data, which is often unavailable.

I tried to use Geofences once, and I found them very inaccurate. I switched to LocationManager making it use pure GPS location and it met my expectations.

Please see this answer, which advises to

Poll the GPS hardware on an interval without doing anything with the result and you'll start getting more accurate geofences.

I have never tried Google's FusedLocation API, but I have heard people saying it worked very well for them.

If you use LocationManager, you will have to implement your 'Geofencing logic' yourself; you can easily do it with Location.distanceTo(Location).

Example:

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

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

2) CPU is not active

The fact that the Geofences are active, does not necessarily mean that your phone is awake and computing location checks.

To fix that, you can start a ForegroundService from your BroacastReceiver. The Service should hold a partial WakeLock as well. This guarantees that:

  1. The OS does not kill the service (or better: less chance to be killed...)
  2. The user is aware of the service and can dismiss it if necessary
  3. The CPU is running. Therefore you can be sure that the code that retrieves the location is running (please remember to to release the WakeLock when the service stops).

Please note that Android may still kill your service if necessary.

You can find plenty of examples on the web on how to start a ForegroundService from a BroadcastReceiver, how to hold a WakeLock and so on...

Also, check out to the new Android O API, that brought some minor changes to the ForegroundService and other components.

PS: I have developed and application that uses all the components mentioned above (except for the FusedLocation) and I was extremely satisfied.

EDIT: Answering OP's questions

Okey, let's try to make some order here, otherwise future readers may easily get confused. I'll start by answering what written in the original question and the 'bounty banner', then the OP edits, and finally the questions the OP placed in the comments.

1) Original question

Is the triggering event also being dismissed, when the app is cleaned by the garbage collector?

Most probably yes. See this answer where OP implemented a service that runs in a separate process, in order to make geofence be triggered even when the app is killed.

I need to understand what causes the geofences not to get called, if enough time has passed

Plenty of reasons. See my original answer.

I saw an implementation of the geofence logic with an Service instead of a broadcast receiver, will that work better?

A Receiver and a Service are two different things. Please read Android's documentation. You can start a Service from a BroadcastReceiver, which is usually the preferred way to 'receive' PendingIntents and do something with them.

2) Edits

  • Please note that I did not tell you to replace the BroadcastReceiver with a Service, but that it might be a good idea to start a Service from your Receiver and handle all your logic there.
  • Making your IntentService a Singleton class is not necessary as (from IntentService documentation)

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

  • Do not store Context into a Singleton class or some static references. I'm impressed Android Studio did not warn you.

3) Comments

I need this to work 24/7 hence I cannot use the location all the time, cause of obvious battery issues.

Please read Android Oreo Background Execution Limits. This might be an issue for you.

Also now that I changed to a intentService, is that enough to ensure it should stay awake?

No, as I said, you probably need a partial WakeLock in order to turn on the CPU.

Do I need to initiate it another way, in order to keep it in the foreground?

Yes. In order to start a Foreground Service, you need to call startForeground(int, Notification)

Please note: IntentServices lifespan is limited to the end of the onHandleIntent() function. They are not supposed to live for more than a few seconds, typically. Use the Service class if you want to start a Foreground.

Moreover, as said in the original answer, a new Foreground API is available and preferred for Android Oreo.

Not a question, just a notice: I need to use here Geofencing. (Geofencing will start if necessary the gps

Ok perfect. See what works best for you.

这篇关于地理围栏事件并不总是被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆