Saturday, March 16, 2019

Android开发笔记-ch3.4.21 GPS


3.4.21 GPS

The Fused location provider manages the underlying location technologies, such as GPS and Wi-Fi, and provides a simple API that you can use to specify the required quality of service.
Below is an example of logcat output for enable GPS->start Google Map->Exit Google Map-> disable Gps
C:\work\log>adb logcat -v time *:D | grep -i gps
02-09 21:06:32.234 E/LocSvc_eng( 833): I/===> void loc_eng_agps_init(loc_eng_data_s_type&, AGpsExtCallbacks*) line 2058
02-09 21:06:32.234 E/LocSvc_eng( 833): W/void loc_eng_agps_init(loc_eng_data_s_type&, AGpsExtCallbacks*): log_eng state error: agps instance already initialized
02-09 21:06:32.234 E/LocSvc_eng( 833): I/===> void loc_eng_ni_init(loc_eng_data_s_type&, GpsNiExtCallbacks*) line 290
02-09 21:06:59.974 E/LocSvc_eng( 833): I/<=== status_cb line 1939 GPS_STATUS_SESSION_BEGIN
02-09 21:07:13.778 E/LocSvc_eng( 833): I/<=== status_cb line 1939 GPS_STATUS_SESSION_END
02-09 21:07:20.055 I/GeofencerStateMachine( 1084): GPS disabled.
Google Map is running between the highlighted two lines above, and the Gps icon shows up in the same period.
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
if (location != null) try {lat=location.getLatitude(); lon=location.getLongitude();} catch {...}
Above is simple code to get location. Use LocationManager.GPS_PROVIDER instead of above bestProvider to force using Gps.
Calling locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this) won't guarantee it report location by calling onLocationChanged every 3 seconds, unless the location is changed over 10m. Note above code is using this as LocationListener argument, as the activity implements LocationListener interface, in that case, in the activity onPause, has to call locationManager.removeUpdates(this). Otherwise, won't be able to remove the callback properly. The other way is do not implement the interface, instead, create instance of listener as class member, as mentioned in here and location strategies.

0 Comments:

Post a Comment