@@ -183,6 +183,60 @@ public static String getStreet(double latitude, double longitude) {
183
183
Address address = getAddress (latitude , longitude );
184
184
return address == null ? "unknown" : address .getAddressLine (0 );
185
185
}
186
+
187
+ /** Determines whether one Location reading is better than the current Location fix
188
+ * @param newLocation The new Location that you want to evaluate
189
+ * @param currentBestLocation The current Location fix, to which you want to compare the new one
190
+ */
191
+ static boolean isBetterLocation (Location newLocation , Location currentBestLocation ) {
192
+ if (currentBestLocation == null ) {
193
+ // A new location is always better than no location
194
+ return true ;
195
+ }
196
+
197
+ // Check whether the new location fix is newer or older
198
+ long timeDelta = newLocation .getTime () - currentBestLocation .getTime ();
199
+ boolean isSignificantlyNewer = timeDelta > TWO_MINUTES ;
200
+ boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES ;
201
+ boolean isNewer = timeDelta > 0 ;
202
+
203
+ // If it's been more than two minutes since the current location, use the new location
204
+ // because the user has likely moved
205
+ if (isSignificantlyNewer ) {
206
+ return true ;
207
+ // If the new location is more than two minutes older, it must be worse
208
+ } else if (isSignificantlyOlder ) {
209
+ return false ;
210
+ }
211
+
212
+ // Check whether the new location fix is more or less accurate
213
+ int accuracyDelta = (int ) (newLocation .getAccuracy () - currentBestLocation .getAccuracy ());
214
+ boolean isLessAccurate = accuracyDelta > 0 ;
215
+ boolean isMoreAccurate = accuracyDelta < 0 ;
216
+ boolean isSignificantlyLessAccurate = accuracyDelta > 200 ;
217
+
218
+ // Check if the old and new location are from the same provider
219
+ boolean isFromSameProvider = isSameProvider (newLocation .getProvider (),
220
+ currentBestLocation .getProvider ());
221
+
222
+ // Determine location quality using a combination of timeliness and accuracy
223
+ if (isMoreAccurate ) {
224
+ return true ;
225
+ } else if (isNewer && !isLessAccurate ) {
226
+ return true ;
227
+ } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider ) {
228
+ return true ;
229
+ }
230
+ return false ;
231
+ }
232
+
233
+ /** Checks whether two providers are the same */
234
+ static boolean isSameProvider (String provider1 , String provider2 ) {
235
+ if (provider1 == null ) {
236
+ return provider2 == null ;
237
+ }
238
+ return provider1 .equals (provider2 );
239
+ }
186
240
187
241
private static class MyLocationListener
188
242
implements LocationListener {
@@ -263,4 +317,4 @@ public interface OnLocationChangeListener {
263
317
*/
264
318
void onStatusChanged (String provider , int status , Bundle extras );//位置状态发生改变
265
319
}
266
- }
320
+ }
0 commit comments