如何获得在地理围栏中的停留时间?

How to get residence time in a geofence?

简单的问题需要简单的回答。 如何跟踪特定地理围栏中的停留时间。 当我使用 Trigger on Enter 添加地理围栏时,我会在离开该地理围栏时自动收到触发器。基本上我需要记住我进入地理围栏和离开地理围栏的时间,这样我就可以减去离开-进入时间并得到我的持续时间。但我相信做到这一点并不容易。那么还有其他想法或建议如何有效解决该问题吗? 谢谢

我找到了解决这个问题的方法。为了确定地理围栏中的停留时间,我必须获得用户触发地理围栏的时间,然后我使用这种数学方法计算用户是否离开地理围栏

 Handler handler = new Handler();
    getCurrentLatLng();
    final Runnable myRunnable = new Runnable() {
        public void run() {
            GeofenceFinished myFinishedGeofence = db.getGeofenceFinishedByID("Finished" + id);
            if (!isUserInRegion(latitude, longitude, myLatLng.latitude, myLatLng.longitude, rd)
                    || myFinishedGeofence == null) {
                String time = convertTime(endTime - startTime);
                // get the finishedGeofence and set the duration of stay time
                if (myFinishedGeofence != null)
                    setDurationOfStay("Finished" + id, time, getCurrentTime(System.currentTimeMillis()));
                Toast.makeText(mContext, "Finish to determine duration of stay of " + myFinishedGeofence.getAddress(), Toast.LENGTH_SHORT).show();
                handler.removeCallbacks(this);
            } else {
                getCurrentLatLng();
                endTime += Constants.DELAY;
                handler.postDelayed(this, Constants.DELAY);
            }
        }

        private void setDurationOfStay(String geofenceid, String time, String endTime) {
            if (db == null) db = GeofenceDatabaseHelper.getInstance(mContext);
            if (!db.setDurationOfFinishedGeofence(geofenceid, time, endTime)) {
                Log.i("setDurationOfStay", "fail");
            }
        }
    };
    handler.postDelayed(myRunnable, Constants.DELAY);

private boolean isUserInRegion(double firstLat, double firstLog, double curLat, double curLog, float radius) {
    double distance = calculateDistance(firstLat, firstLog, curLat, curLog);
    return distance <= radius;
}

要计算用户与地理围栏中心的距离,我需要将当前的纬度和经度转换为米,因此我可以使用参数 equation for circle

进行计算

所以我使用了 github

中的这种方法
    // https://github.com/mgavaghan/geodesy
private double calculateDistance(double firstLat, double firstLog, double curLat, double curLog) {
    GeodeticCalculator geoCalc = new GeodeticCalculator();
    Ellipsoid reference = Ellipsoid.WGS84;
    GlobalPosition pointA = new GlobalPosition(firstLat, firstLog, 0.0); // Point A
    GlobalPosition userPos = new GlobalPosition(curLat, curLog, 0.0); // Point B
    // Distance between Point A and Point B
    double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance();
    return distance;
}

希望对某人有所帮助 :D