blob: f63607a2a4ec42c27f68bf706ea1cbad197edd20 [file] [log] [blame]
Nick Pellye0fd6932012-07-11 10:26:13 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package com.android.server.location;
19
20import android.location.Location;
21
22/**
23 * Represents a simple circular GeoFence.
24 */
25public class Geofence {
26 public final static int FLAG_ENTER = 0x01;
27 public final static int FLAG_EXIT = 0x02;
28
29 static final int STATE_UNKNOWN = 0;
30 static final int STATE_INSIDE = 1;
31 static final int STATE_OUTSIDE = 2;
32
33 final double mLatitude;
34 final double mLongitude;
35 final float mRadius;
36 final Location mLocation;
37
38 int mState; // current state
39 double mDistance; // current distance to center of fence
40
41 public Geofence(double latitude, double longitude, float radius, Location prevLocation) {
42 mState = STATE_UNKNOWN;
43
44 mLatitude = latitude;
45 mLongitude = longitude;
46 mRadius = radius;
47
48 mLocation = new Location("");
49 mLocation.setLatitude(latitude);
50 mLocation.setLongitude(longitude);
51
52 if (prevLocation != null) {
53 processLocation(prevLocation);
54 }
55 }
56
57 /**
58 * Process a new location.
59 * @return FLAG_ENTER or FLAG_EXIT if the fence was crossed, 0 otherwise
60 */
61 public int processLocation(Location location) {
62 mDistance = mLocation.distanceTo(location);
63
64 int prevState = mState;
65 //TODO: inside/outside detection could be made more rigorous
66 boolean inside = mDistance <= Math.max(mRadius, location.getAccuracy());
67 if (inside) {
68 mState = STATE_INSIDE;
69 } else {
70 mState = STATE_OUTSIDE;
71 }
72
73 if (prevState != 0 && mState != prevState) {
74 if (mState == STATE_INSIDE) return FLAG_ENTER;
75 if (mState == STATE_OUTSIDE) return FLAG_EXIT;
76 }
77 return 0;
78 }
79
80 public double getDistance() {
81 return mDistance;
82 }
83
84 @Override
85 public String toString() {
86 String state;
87 switch (mState) {
88 case STATE_INSIDE:
89 state = "IN";
90 break;
91 case STATE_OUTSIDE:
92 state = "OUT";
93 break;
94 default:
95 state = "?";
96 }
97 return String.format("(%.4f, %.4f r=%.0f d=%.0f %s)", mLatitude, mLongitude, mRadius,
98 mDistance, state);
99 }
100}