本文轉自http://blog.csdn.net/xnwyd/article/details/7198728,謝謝作者!
1 GPS架構

2 GPS分析
2.1 頭檔案
頭檔案定義在:hardware/libhardware/include/hardware/gps.h,定義了GPS底層相關的結構體和接口
- GpsLocation
GPS位置資訊結構體,包含經緯度,高度,速度,方位角等。
[cpp] view plain copy
- typedef uint16_t GpsLocationFlags;
- // IMPORTANT: Note that the following values must match
- // constants in GpsLocationProvider.java.
- #define GPS_LOCATION_HAS_LAT_LONG 0x0001
- #define GPS_LOCATION_HAS_ALTITUDE 0x0002
- #define GPS_LOCATION_HAS_SPEED 0x0004
- #define GPS_LOCATION_HAS_BEARING 0x0008
- #define GPS_LOCATION_HAS_ACCURACY 0x0010
- typedef struct {
- size_t size;
- uint16_t flags;
- double latitude;
- double longitude;
- double altitude;
- float speed;
- float bearing;
- float accuracy;
- GpsUtcTime timestamp;
- } GpsLocation;
- GpsStatus
GPS狀态包括5種狀态,分别為未知,正在定位,停止定位,啟動未定義,未啟動。
[cpp] view plain copy
- typedef uint16_t GpsStatusValue;
- // IMPORTANT: Note that the following values must match
- // constants in GpsLocationProvider.java.
- #define GPS_STATUS_NONE 0
- #define GPS_STATUS_SESSION_BEGIN 1
- #define GPS_STATUS_SESSION_END 2
- #define GPS_STATUS_ENGINE_ON 3
- AgpsCallbacks
- AgpsInterface
- #define GPS_STATUS_ENGINE_OFF 4
- typedef struct {
- size_t size;
- GpsStatusValue status;
- } GpsStatus;
- GpsSvInfo
GPS衛星資訊,包含衛星編号,信号強度,衛星仰望角,方位角等。
[cpp] view plain copy
- typedef struct {
- size_t size;
- int prn;
- float snr;
- float elevation;
- float azimuth;
- } GpsSvInfo;
- GpsSvStatus
GPS衛星狀态,包含可見衛星數和資訊,星曆時間,年曆時間等。
[cpp] view plain copy
- typedef struct {
- size_t size;
- int num_svs;
- GpsSvInfo sv_list[GPS_MAX_SVS];
- uint32_t ephemeris_mask;
- uint32_t almanac_mask;
- uint32_t used_in_fix_mask;
- } GpsSvStatus;
- GpsCallbacks
回調函數定義
[cpp] view plain copy
- typedef void (* gps_location_callback)(GpsLocation* location);
- typedef void (* gps_status_callback)(GpsStatus* status);
- typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
- typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);
- typedef void (* gps_set_capabilities)(uint32_t capabilities);
- typedef void (* gps_acquire_wakelock)();
- 釋放鎖
- typedef void (* gps_release_wakelock)();
- typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);
- typedef struct {
- size_t size;
- gps_location_callback location_cb;
- gps_status_callback status_cb;
- gps_sv_status_callback sv_status_cb;
- gps_nmea_callback nmea_cb;
- gps_set_capabilities set_capabilities_cb;
- gps_acquire_wakelock acquire_wakelock_cb;
- gps_release_wakelock release_wakelock_cb;
- gps_create_thread create_thread_cb;
- } GpsCallbacks;
- GpsInterface
GPS接口是最重要的結構體,上層是通過此接口與硬體适配層互動的。
[cpp] view plain copy
- typedef struct {
- size_t size;
- int (*init)( GpsCallbacks* callbacks );
- int (*start)( void );
- int (*stop)( void );
- void (*cleanup)( void );
- int (*inject_time)(GpsUtcTime time, int64_t timeReference,
- int uncertainty);
- int (*inject_location)(double latitude, double longitude, float accuracy);
- void (*delete_aiding_data)(GpsAidingData flags);
- int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
- uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);
- const void* (*get_extension)(const char* name);
- } GpsInterface;
- gps_device_t
GPS裝置結構體,繼承自hw_device_tcommon,硬體适配接口,向上層提供了重要的get_gps_interface接口。
[cpp] view plain copy
- struct gps_device_t {
- struct hw_device_t common;
- const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
- };
2.2硬體适配層
GPS硬體适配層的源碼位于:hardware/qcom/gps目錄下。
我們看gps/loc_api/llibloc_api/gps.c,首先定義了gps裝置子產品執行個體:
[cpp] view plain copy
- const struct hw_module_t HAL_MODULE_INFO_SYM = {
- .tag = HARDWARE_MODULE_TAG,
- .version_major = 1,
- .version_minor = 0,
- .id = GPS_HARDWARE_MODULE_ID,
- .name = "loc_api GPS Module",
- .author = "Qualcomm USA, Inc.",
- .methods = &gps_module_methods,
- };
這裡的methods指向gps.c檔案中的gps_module_methods
[cpp] view plain copy
- static struct hw_module_methods_t gps_module_methods = {
- .open = open_gps
- };
gps_module_methods定義了裝置的open函數為open_gps,我們看open_gps函數:
[cpp] view plain copy
- static int open_gps(const struct hw_module_t* module, char const* name,
- struct hw_device_t** device)
- {
- struct gps_device_t *dev = malloc(sizeof(struct gps_device_t));
- memset(dev, 0, sizeof(*dev));
- dev->common.tag = HARDWARE_DEVICE_TAG;
- dev->common.version = 0;
- dev->common.module = (struct hw_module_t*)module;
- dev->get_gps_interface = gps__get_gps_interface;
- *device = (struct hw_device_t*)dev;
- return 0;
- }
此處可以看作是GPS裝置的初始化函數,在使用裝置前必須執行此函數。函數裡面指定了hw_device_t的module成員,以及gps_device_t的get_gps_interface成員。上層可通過gps_device_t的get_gps_interface調用gps__get_gps_interface函數。gps__get_gps_interface的定義如下:
[cpp] view plain copy
- const GpsInterface* gps__get_gps_interface(struct gps_device_t* dev)
- {
- return get_gps_interface();
- }
用代碼跟蹤可看到,此函數傳回了gps/loc_eng.cpp檔案的sLocEngInterface變量,sLocEngInterface定義如下:
[cpp] view plain copy
- // Defines the GpsInterface in gps.h
- static const GpsInterface sLocEngInterface =
- {
- sizeof(GpsInterface),
- loc_eng_init,
- loc_eng_start,
- loc_eng_stop,
- loc_eng_cleanup,
- loc_eng_inject_time,
- loc_eng_inject_location,
- loc_eng_delete_aiding_data,
- loc_eng_set_position_mode,
- loc_eng_get_extension,
- };
sLocEngInterface指定了GpsInterface結構體的各個回調函數,如啟動定位/取消定位等,這些回調函數的實作均在loc_eng.cpp中實作。
2.2 JNI适配層
GPSJNI适配層的源碼位于:frameworks/base/services/jni/com_android_server_location_GpsLocationProvider.cpp
首先看注冊JNI方法的函數定義:
[plain] view plain copy
- int register_android_server_location_GpsLocationProvider(JNIEnv* env)
- {
- return jniRegisterNativeMethods(env, "com/android/server/location/GpsLocationProvider", sMethods, NELEM(sMethods));
- }
此函數被同目錄下onload.cpp檔案調用,調用地方在:
[cpp] view plain copy
- extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
- {
- JNIEnv* env = NULL;
- jint result = -1;
- if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
- LOGE("GetEnv failed!");
- return result;
- }
- LOG_ASSERT(env, "Could not retrieve the env!");
- //...省略其他注冊代碼
- register_android_server_location_GpsLocationProvider(env);
- return JNI_VERSION_1_4;
- }
從這裡可以看到,JNI初始化的時候,即會進行JNI方法的注冊,進而使上層應用能通過JNI調用c/c++本地方法。
回到register_android_server_location_GpsLocationProvider函數,變量sMethods定義如下:
[cpp] view plain copy
- static JNINativeMethod sMethods[] = {
- {"class_init_native", "()V", (void *)android_location_GpsLocationProvider_class_init_native},
- {"native_is_supported", "()Z", (void*)android_location_GpsLocationProvider_is_supported},
- {"native_init", "()Z", (void*)android_location_GpsLocationProvider_init},
- {"native_cleanup", "()V", (void*)android_location_GpsLocationProvider_cleanup},
- {"native_set_position_mode", "(IIIII)Z", (void*)android_location_GpsLocationProvider_set_position_mode},
- {"native_start", "()Z", (void*)android_location_GpsLocationProvider_start},
- {"native_stop", "()Z", (void*)android_location_GpsLocationProvider_stop},
- {"native_delete_aiding_data", "(I)V", (void*)android_location_GpsLocationProvider_delete_aiding_data},
- {"native_read_sv_status", "([I[F[F[F[I)I", (void*)android_location_GpsLocationProvider_read_sv_status},
- {"native_read_nmea", "([BI)I", (void*)android_location_GpsLocationProvider_read_nmea},
- {"native_inject_time", "(JJI)V", (void*)android_location_GpsLocationProvider_inject_time},
- {"native_inject_location", "(DDF)V", (void*)android_location_GpsLocationProvider_inject_location},
- {"native_supports_xtra", "()Z", (void*)android_location_GpsLocationProvider_supports_xtra},
- {"native_inject_xtra_data", "([BI)V", (void*)android_location_GpsLocationProvider_inject_xtra_data},
- {"native_agps_data_conn_open", "(Ljava/lang/String;)V", (void*)android_location_GpsLocationProvider_agps_data_conn_open},
- {"native_agps_data_conn_closed", "()V", (void*)android_location_GpsLocationProvider_agps_data_conn_closed},
- {"native_agps_data_conn_failed", "()V", (void*)android_location_GpsLocationProvider_agps_data_conn_failed},
- {"native_agps_set_id","(ILjava/lang/String;)V",(void*)android_location_GpsLocationProvider_agps_set_id},
- {"native_agps_set_ref_location_cellid","(IIIII)V",(void*)android_location_GpsLocationProvider_agps_set_reference_location_cellid},
- {"native_set_agps_server", "(ILjava/lang/String;I)V", (void*)android_location_GpsLocationProvider_set_agps_server},
- {"native_send_ni_response", "(II)V", (void*)android_location_GpsLocationProvider_send_ni_response},
- {"native_agps_ni_message", "([BI)V", (void *)android_location_GpsLocationProvider_agps_send_ni_message},
- {"native_get_internal_state", "()Ljava/lang/String;", (void*)android_location_GpsLocationProvider_get_internal_state},
- {"native_update_network_state", "(ZIZLjava/lang/String;)V", (void*)android_location_GpsLocationProvider_update_network_state },
- };
這裡定義了GPS所有向上層提供的JNI本地方法,這些本地方法是如何與硬體适配層互動的呢?我們看其中一個本地方法android_location_GpsLocationProvider_start:
[cpp] view plain copy
- static jboolean android_location_GpsLocationProvider_start(JNIEnv* env, jobject obj)
- {
- const GpsInterface* interface = GetGpsInterface(env, obj);
- if (interface)
- return (interface->start() == 0);
- else
- return false;
- }
它調用了GetGpsInterface獲得GpsInterface接口,然後直接調用該接口的start回調函數。GetGpsInterface方法定義如下:
[cpp] view plain copy
- static const GpsInterface* GetGpsInterface(JNIEnv* env, jobject obj) {
- // this must be set before calling into the HAL library
- if (!mCallbacksObj)
- mCallbacksObj = env->NewGlobalRef(obj);
- if (!sGpsInterface) {
- sGpsInterface = get_gps_interface();
- if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0) {
- sGpsInterface = NULL;
- return NULL;
- }
- }
- return sGpsInterface;
- }
這個函數傳回了sGpsInterface,而sGpsInterface又是從get_gps_interface()獲得的,我們繼續檢視get_gps_interface()函數的實作:
[cpp] view plain copy
- static const GpsInterface* get_gps_interface() {
- int err;
- hw_module_t* module;
- const GpsInterface* interface = NULL;
- err = hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);
- if (err == 0) {
- hw_device_t* device;
- err = module->methods->open(module, GPS_HARDWARE_MODULE_ID, &device);
- if (err == 0) {
- gps_device_t* gps_device = (gps_device_t *)device;
- interface = gps_device->get_gps_interface(gps_device);
- }
- }
- return interface;
- }
這裡面調用hw_get_module加載硬體适配子產品.so檔案,接着通過hw_device_t接口調用open()函數,實際執行gps/loc_api/llibloc_api/gps.c定義的open_gps函數,而後調用gps_device_t接口的get_gps_interface函數,此函數也是在gps.c中定義的,最後傳回硬體适配層中loc_eng.cpp檔案的sLocEngInterface,進而打通了上層到底層的通道。
2.3 Java Framework
GPSFramework源碼位于:frameworks/base/location
2.3.1接口和類簡介
首先對GPSFramework重要的接口和類作一個簡單的介紹
- 接口
GpsStatus.Listener | 用于當Gps狀态發生變化時接收通知 |
GpsStatus.NmeaListener | 用于接收Gps的NMEA資料 |
LocationListener | 用于接收當位置資訊發生變化時,LocationManager發出的通知 |
- 類
Address | 位址資訊類 |
Criteria | 用于根據裝置情況動态選擇provider |
Geocoder | 用于處理地理編碼資訊 |
GpsSatellite | 用于擷取目前衛星狀态 |
GpsStatus | 用于擷取目前Gps狀态 |
Location | 地理位置資訊類 |
LocationManager | 用于擷取和操作gps系統服務 |
LocationProvider | 抽象類,用于提供位置提供者(Locationprovider) |
2.3.2 使用Gps程式設計接口
下面,我們用一個代碼示例說明如何在應用層寫一個簡單的gps程式。
- 首先在AndroidManifest.xml中添加位置服務權限:
[plain] view plain copy
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_FIND_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
- 接着擷取位置資訊:
[java] view plain copy
- //擷取位置服務
- LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- Criteria criteria = new Criteria();
- // 獲得最好的定位效果
- criteria.setAccuracy(Criteria.ACCURACY_FINE); //設定為最大精度
- criteria.setAltitudeRequired(false); //不擷取海拔資訊
- criteria.setBearingRequired(false); //不擷取方位資訊
- criteria.setCostAllowed(false); //是否允許付費
- criteria.setPowerRequirement(Criteria.POWER_LOW); // 使用省電模式
- // 獲得目前的位置提供者
- String provider = locationManager.getBestProvider(criteria, true);
- // 獲得目前的位置
- Location location = locationManager.getLastKnownLocation(provider);
- Geocoder gc = new Geocoder(this);
- List<Address> addresses = null;
- try {
- //根據經緯度獲得位址資訊
- addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
- } catch (IOException e) {
- e.printStackTrace();
- } if (addresses.size() > 0) {
- //擷取address類的成員資訊
- Sring msg = “”;
- msg += "AddressLine:" + addresses.get(0).getAddressLine(0)+ "\n";
- msg += "CountryName:" + addresses.get(0).getCountryName()+ "\n";
- msg += "Locality:" + addresses.get(0).getLocality() + "\n";
- msg += "FeatureName:" + addresses.get(0).getFeatureName();
- }
- 設定偵聽,當位置資訊發生變化時,自動更新相關資訊
[java] view plain copy
- //匿名類,繼承自LocationListener接口
- private final LocationListener locationListener = new LocationListener() {
- public void onLocationChanged(Location location) {
- updateWithNewLocation(location);//更新位置資訊
- }
- public void onProviderDisabled(String provider){
- updateWithNewLocation(null);//更新位置資訊
- }
- public void onProviderEnabled(String provider){ }
- public void onStatusChanged(String provider, int status,Bundle extras){ }
- };
- //更新位置資訊
- private void updateWithNewLocation(Location location) {
- if (location != null) {
- //擷取經緯度
- double lat = location.getLatitude();
- double lng = location.getLongitude();
- }
- //添加偵聽
- locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);
2.3.3接口和類分析
下面對相關的類或接口進行分析,LocationManager的代碼檔案位于:frameworks/base/location/java/location/LocationManager.java
我們看其構造函數:
[java] view plain copy
- public LocationManager(ILocationManager service) {
- mService = service;
- }
其中mService為ILocationManager接口類型,構造函數的參數為service,外部調用時傳入LocationManagerService執行個體。LocationManager是android系統的gps位置資訊系統服務,在稍後将會對其進行分析。由帶參構造函數執行個體化LocationManager類的方式用得不多,一般用的方式是由getSystemService獲得LocationManagerService服務,再強制轉換為LocationManager。例如在2.3.2中的代碼示例中是這樣擷取gps服務的:
[java] view plain copy
- LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
這裡的Context.LOCATION_SERVICE為”location”,辨別gps服務。
LocationManagerService服務是整個GpsFramework的核心,首先看它是如何加載的,代碼檔案位于:frameworks/base/services/java/com/android/server/systemserver.java
[java] view plain copy
- …//省略其他代碼
- LocationManagerService location = null;
- …//省略其他代碼
- try {
- Slog.i(TAG, "Location Manager");
- location = new LocationManagerService(context);
- ServiceManager.addService(Context.LOCATION_SERVICE, location);
- } catch (Throwable e) {
- Slog.e(TAG, "Failure starting Location Manager", e);
- }
此處向ServiceManger系統服務管理器注冊了新的服務,其名稱為”location”,類型為LocationManagerService。注冊此服務後,Java應用程式可通過ServiceManager獲得LocationManagerService的代理接口ILocationManager.Stub,進而調用LocationManagerService提供的接口函數。ILocationManager位于:
frameworks/base/location/java/location/ILocationManager.aidl,其代碼如下:
[java] view plain copy
- interface ILocationManager
- {
- List<String> getAllProviders();
- List<String> getProviders(in Criteria criteria, boolean enabledOnly);
- String getBestProvider(in Criteria criteria, boolean enabledOnly);
- boolean providerMeetsCriteria(String provider, in Criteria criteria);
- void requestLocationUpdates(String provider, in Criteria criteria, long minTime, float minDistance,
- boolean singleShot, in ILocationListener listener);
- void requestLocationUpdatesPI(String provider, in Criteria criteria, long minTime, float minDistance,
- boolean singleShot, in PendingIntent intent);
- void removeUpdates(in ILocationListener listener);
- void removeUpdatesPI(in PendingIntent intent);
- boolean addGpsStatusListener(IGpsStatusListener listener);
- void removeGpsStatusListener(IGpsStatusListener listener);
- // for reporting callback completion
- void locationCallbackFinished(ILocationListener listener);
- boolean sendExtraCommand(String provider, String command, inout Bundle extras);
- void addProximityAlert(double latitude, double longitude, float distance,
- long expiration, in PendingIntent intent);
- void removeProximityAlert(in PendingIntent intent);
- Bundle getProviderInfo(String provider);
- boolean isProviderEnabled(String provider);
- Location getLastKnownLocation(String provider);
- // Used by location providers to tell the location manager when it has a new location.
- // Passive is true if the location is coming from the passive provider, in which case
- // it need not be shared with other providers.
- void reportLocation(in Location location, boolean passive);
- boolean geocoderIsPresent();
- String getFromLocation(double latitude, double longitude, int maxResults,
- in GeocoderParams params, out List<Address> addrs);
- String getFromLocationName(String locationName,
- double lowerLeftLatitude, double lowerLeftLongitude,
- double upperRightLatitude, double upperRightLongitude, int maxResults,
- in GeocoderParams params, out List<Address> addrs);
- void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite,
- boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
- boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy);
- void removeTestProvider(String provider);
- void setTestProviderLocation(String provider, in Location loc);
- void clearTestProviderLocation(String provider);
- void setTestProviderEnabled(String provider, boolean enabled);
- void clearTestProviderEnabled(String provider);
- void setTestProviderStatus(String provider, int status, in Bundle extras, long updateTime);
- void clearTestProviderStatus(String provider);
- // for NI support
- boolean sendNiResponse(int notifId, int userResponse);
- }
android系統通過ILocationManager.aidl檔案自動生成IlocationManager.Stub代理接口,在Java用戶端擷取LocationManagerService的方式如下:
[java] view plain copy
- ILocationManager mLocationManager;
- IBinder b = ServiceManager.getService(Context.LOCATION_SERVICE);
- mLocationManager = IlocationManager.Stub.asInterface(b);
用戶端通過mLocationManager即可操作LocationMangerService繼承自ILocationManager.Stub的的公共接口。之前提到了通過getSystemSerivice方式也可以獲得LocationManagerService,但getSystemService()傳回的是Object,必須轉換為其他接口,我們可以看到之前的是強制轉換為LocationManager類型,而此處由ServiceManager.getService傳回IBinder接口,再通過ILocationManager.Stub轉換為ILocationManager類型,是更加規範的做法。
LocationMangerService的代碼檔案位于:
frameworks/base/services/java/com/android/server/LocationMangerService.java
我們首先看其中的systemReady()函數
[java] view plain copy
- void systemReady() {
- // we defer starting up the service until the system is ready
- Thread thread = new Thread(null, this, "LocationManagerService");
- thread.start();
- }
此處啟動自身服務線程,因LocationMangerService繼承自Runnable接口,當啟動此線程後,會執行繼承自Runnable接口的run()函數,我們看run()函數的定義:
[java] view plain copy
- public void run()
- {
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- Looper.prepare();
- mLocationHandler = new LocationWorkerHandler();
- initialize();
- Looper.loop();
- }
此處調用了initialize()進行初始化,initialize()函數定義如下:
[java] view plain copy
- private void initialize() {
- //...省略其他代碼
- loadProviders();
- //...省略其他代碼
- }
此處調用了loadProviders()函數,loadProviders()函數調用了_loadProvidersLocked(),其代碼如下:
[java] view plain copy
- private void _loadProvidersLocked() {
- // Attempt to load "real" providers first
- if (GpsLocationProvider.isSupported()) {
- // Create a gps location provider
- GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this);
- mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
- mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
- addProvider(gpsProvider);
- mGpsLocationProvider = gpsProvider;
- }
- // create a passive location provider, which is always enabled
- PassiveProvider passiveProvider = new PassiveProvider(this);
- addProvider(passiveProvider);
- mEnabledProviders.add(passiveProvider.getName());
- // initialize external network location and geocoder services
- if (mNetworkLocationProviderPackageName != null) {
- mNetworkLocationProvider =
- new LocationProviderProxy(mContext, LocationManager.NETWORK_PROVIDER,
- mNetworkLocationProviderPackageName, mLocationHandler);
- addProvider(mNetworkLocationProvider);
- }
- if (mGeocodeProviderPackageName != null) {
- mGeocodeProvider = new GeocoderProxy(mContext, mGeocodeProviderPackageName);
- }
- updateProvidersLocked();
- }
在這裡對GpsLocationProvider和NetworkLocationProvider類作了初始化,并添加到provider集合中。GpsLocationProvider和NetworkLocationProvider繼承自LocationProviderInterface接口,分别代表兩種位置提供者(LocationProvider):
(1)LocationManager.GPS_PROVIDER:GPS模式,精度比較高,但是慢而且消耗電力,而且可能因為天氣原因或者障礙物而無法擷取衛星資訊,另外裝置可能沒有GPS子產品(2)LocationManager.NETWORK_PROVIDER:通過網絡擷取定位資訊,精度低,耗電少,擷取資訊速度較快,不依賴GPS子產品。
Android提供criteria類,可根據目前裝置情況動态選擇位置提供者。我們在之前2.3.2的代碼示例中,有這樣一句代碼:
[java] view plain copy
- // 獲得目前的位置提供者
- String provider = locationManager.getBestProvider(criteria, true);
getBestProvider其實是根據Criteria的條件周遊mProviders集合,傳回符合條件的provider名稱。我們再看GpsLocationProvider的實作,其代碼檔案位于:
frameworks/base/services/java/com/android/server/location/GpsLocationProvider.java
在GpsLocationProvider的構造函數中:
[plain] view plain copy
- public GpsLocationProvider(Context context, ILocationManager locationManager) {
- //...省略部分代碼
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(Intents.DATA_SMS_RECEIVED_ACTION);
- intentFilter.addDataScheme("sms");
- intentFilter.addDataAuthority("localhost","7275");
- context.registerReceiver(mBroadcastReciever, intentFilter);
- intentFilter = new IntentFilter();
- intentFilter.addAction(Intents.WAP_PUSH_RECEIVED_ACTION);
- try {
- intentFilter.addDataType("application/vnd.omaloc-supl-init");
- } catch (IntentFilter.MalformedMimeTypeException e) {
- Log.w(TAG, "Malformed SUPL init mime type");
- }
- context.registerReceiver(mBroadcastReciever, intentFilter);
- //...省略部分代碼
- // wait until we are fully initialized before returning
- mThread = new GpsLocationProviderThread();
- mThread.start();
- while (true) {
- try {
- mInitializedLatch.await();
- break;
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
這裡注冊了廣播接受者mBroadcastReciever,用于接收廣播消息,消息過濾在intentFilter中定義。下面看它接收廣播消息時的動作:
[java] view plain copy
- private final BroadcastReceiver mBroadcastReciever = new BroadcastReceiver() {
- @Override public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if (action.equals(ALARM_WAKEUP)) {
- if (DEBUG) Log.d(TAG, "ALARM_WAKEUP");
- startNavigating(false);
- } else if (action.equals(ALARM_TIMEOUT)) {
- if (DEBUG) Log.d(TAG, "ALARM_TIMEOUT");
- hibernate();
- } else if (action.equals(Intents.DATA_SMS_RECEIVED_ACTION)) {
- checkSmsSuplInit(intent);
- } else if (action.equals(Intents.WAP_PUSH_RECEIVED_ACTION)) {
- checkWapSuplInit(intent);
- }
- }
- };
當接收ALARM_EAKEUP時,執行startNavigating函數,當接收到ALARM_TIMEOUT廣播時,執行hibernate函數。這兩個函數很關鍵,下面看他們的實作:
[java] view plain copy
- private void startNavigating(boolean singleShot) {
- //...省略部分代碼
- if (!native_set_position_mode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
- interval, 0, 0)) {
- mStarted = false;
- Log.e(TAG, "set_position_mode failed in startNavigating()");
- return;
- }
- if (!native_start()) {
- mStarted = false;
- Log.e(TAG, "native_start failed in startNavigating()");
- return;
- }
- //...省略部分代碼
- }
看到沒有,這裡調用了native_set_position_mode和native_start方法,而這些方法正是我們之前在JNI适配層提到的注冊的本地方法。同樣的,hibernate函數調用了JNI提供的native_stop方法。我們再看GpsLocationProvider的内部私有函數:
可以看到所有這些本地方法,都是在JNI層注冊的,GpsLocationProvider類是從JNI層到Framework層的通道。
下面回到LocationManagerService,分析如何擷取最新的位置資訊(Location),擷取最新的location的函數是getLastKnownLocation,其實作如下:
[java] view plain copy
- private Location _getLastKnownLocationLocked(String provider) {
- checkPermissionsSafe(provider);
- LocationProviderInterface p = mProvidersByName.get(provider);
- if (p == null) {
- return null;
- }
- if (!isAllowedBySettingsLocked(provider)) {
- return null;
- }
- return mLastKnownLocation.get(provider);
- }
這裡mLastKnownLocation類型為HashMap<String,Location>,是以mLastKnownLocation.get(provider)表示通過provider的名稱在哈希字典中擷取相應的location,那麼這些location是什麼時候被存入到哈希字典中的呢?
我們回到LocationManagerService的run函數:
[java] view plain copy
- public void run()
- {
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- Looper.prepare();
- mLocationHandler = new LocationWorkerHandler();
- initialize();
- Looper.loop();
- }
這裡對類型為LocationWorkerHandler的變量進行初始化,LocationWorkerHandler是在LocationManagerService的一個内部類,它繼承自Handler類,Handler是Android系統用于應用程式内部通信的元件,内部通信指同個程序的主線程與其他線程間的通信,Handler通過Message或Runnable對象進行通信。我們繼續看LocationWorkerHandler的實作:
[java] view plain copy
- private class LocationWorkerHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- try {
- if (msg.what == MESSAGE_LOCATION_CHANGED) {
- // log("LocationWorkerHandler: MESSAGE_LOCATION_CHANGED!");
- synchronized (mLock) {
- Location location = (Location) msg.obj;
- String provider = location.getProvider();
- boolean passive = (msg.arg1 == 1);
- if (!passive) {
- // notify other providers of the new location
- for (int i = mProviders.size() - 1; i >= 0; i--) {
- LocationProviderInterface p = mProviders.get(i);
- if (!provider.equals(p.getName())) {
- p.updateLocation(location);
- }
- }
- }
- if (isAllowedBySettingsLocked(provider)) {
- handleLocationChangedLocked(location, passive);
- }
- }
- } else if (msg.what == MESSAGE_PACKAGE_UPDATED) {
- //...省略部分代碼
- }
- }
- } catch (Exception e) {
- // Log, don't crash!
- Slog.e(TAG, "Exception in LocationWorkerHandler.handleMessage:", e);
- }
- }
- }
這裡重寫Handle類的handleMessage方法,處理用Handle接收的Message對象消息。當接受到位置資訊變化的消息MESSAGE_LOCATION_CHANGED時,調用p.updateLocationhandleLocationChangedLocked方法,其實作如下:
[java] view plain copy
- private void handleLocationChangedLocked(Location location, boolean passive) {
- //...省略部分代碼
- // Update last known location for provider
- Location lastLocation = mLastKnownLocation.get(provider);
- if (lastLocation == null) {
- mLastKnownLocation.put(provider, new Location(location));
- } else {
- lastLocation.set(location);
- }
- //...省略部分代碼
- }
可以看到是在handleLocationChangedLocked函數中實作對lastknownlocation的更新的,那麼在LocationWorkerHandler類中處理的MESSAGE_LOCATION_CHANGED消息是誰發送出來的呢?答案是在LocationManagerService類的reportLocation函數中:
[java] view plain copy
- public void reportLocation(Location location, boolean passive) {
- if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
- != PackageManager.PERMISSION_GRANTED) {
- throw new SecurityException("Requires INSTALL_LOCATION_PROVIDER permission");
- }
- mLocationHandler.removeMessages(MESSAGE_LOCATION_CHANGED, location);
- Message m = Message.obtain(mLocationHandler, MESSAGE_LOCATION_CHANGED, location);
- m.arg1 = (passive ? 1 : 0);
- mLocationHandler.sendMessageAtFrontOfQueue(m);
- }
此處構造了新的Message對象,然後發送到消息隊列的首位置。在GpsLocationProvider類的reportLocation函數中,有這樣一段代碼:
[java] view plain copy
- try {
- mLocationManager.reportLocation(mLocation, false);
- } catch (RemoteException e) {
- Log.e(TAG, "RemoteException calling reportLocation");
- }
是以實際是由GpsLocationProvider主動調用LocationManagerService的reportLocation方法,進而更新最新的位置資訊。
實際上,GpsLocationoProvider的reportLocation對應了硬體适配層中的GpsCallbacks結構體中的回調函數gps_location_callback
[cpp] view plain copy
- typedef void (* gps_location_callback)(GpsLocation* location);
那麼GpsLocationProvider中的reportLocation函數是如何與GpsCallbacks的gps_location_callback挂鈎的呢?我們回到JNI适配層的代碼檔案:
frameworks/base/services/jni/com_android_server_location_GpsLocationProvider.cpp
其中定義的GetGpsInterface函數:
[cpp] view plain copy
- static const GpsInterface* GetGpsInterface(JNIEnv* env, jobject obj) {
- // this must be set before calling into the HAL library
- if (!mCallbacksObj)
- mCallbacksObj = env->NewGlobalRef(obj);
- if (!sGpsInterface) {
- sGpsInterface = get_gps_interface();
- if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0) {
- sGpsInterface = NULL;
- return NULL;
- }
- }
- return sGpsInterface;
- }
這裡面的sGpsInterface->init(&sGpsCallbacks)調用了GpsInterface的init回調函數,即初始化GpsCallbacks結構體變量sGpsCallbacks,sGpsCallbacks定義如下:
[cpp] view plain copy
- GpsCallbacks sGpsCallbacks = {
- sizeof(GpsCallbacks),
- location_callback,
- status_callback,
- sv_status_callback,
- nmea_callback,
- set_capabilities_callback,
- acquire_wakelock_callback,
- release_wakelock_callback,
- create_thread_callback,
- };
我們再次看GpsCallbacks的定義(其代碼檔案在硬體适配層的頭檔案gps.h中):
[cpp] view plain copy
- typedef struct {
- size_t size;
- gps_location_callback location_cb;
- gps_status_callback status_cb;
- gps_sv_status_callback sv_status_cb;
- gps_nmea_callback nmea_cb;
- gps_set_capabilities set_capabilities_cb;
- gps_acquire_wakelock acquire_wakelock_cb;
- gps_release_wakelock release_wakelock_cb;
- gps_create_thread create_thread_cb;
- } GpsCallbacks;
比較sGpsCallbacks與GpsCallbacks,可以看到location_callback與gps_location_callback對應。再看location_callback函數的定義:
[cpp] view plain copy
- static void location_callback(GpsLocation* location)
- {
- JNIEnv* env = AndroidRuntime::getJNIEnv();
- env->CallVoidMethod(mCallbacksObj, method_reportLocation, location->flags,
- (jdouble)location->latitude, (jdouble)location->longitude,
- (jdouble)location->altitude,
- (jfloat)location->speed, (jfloat)location->bearing,
- (jfloat)location->accuracy, (jlong)location->timestamp);
- checkAndClearExceptionFromCallback(env, __FUNCTION__);
- }
這裡面利用JNI調用了Java語言的方法method_reportLocation,method_reportLocation是一個jmethodID變量,表示一個由Java語言定義的方法。下面我們看method_reportLocation的指派代碼:
[cpp] view plain copy
- static void android_location_GpsLocationProvider_class_init_native(JNIEnv* env, jclass clazz) {
- method_reportLocation = env->GetMethodID(clazz, "reportLocation", "(IDDDFFFJ)V");
- //...省略部分代碼
- }
這裡表示method_reportLocation指向Java類clazz裡的方法reportLocation,那麼這個Java類clazz是不是表示GpsLocationProvider呢?我們找到注冊JNI方法的方法表:
[cpp] view plain copy
- tatic JNINativeMethod sMethods[] = {
- {"class_init_native", "()V", (void *)android_location_GpsLocationProvider_class_init_native},
- //...省略部分代碼
- }
這裡說明_GpsLocationProvider_class_init_native對應的native方法名稱是class_init_native,下面我們隻要确定在Java中的某個類A調用了class_init_native方法,即可以說明A類的reportLocation函數是GpsCallbacks的回調函數。
我們回到GpsLocationProvider的代碼檔案:
frameworks/base/services/java/com/android/server/location/GpsLocationProvider.java
其中有一段代碼:
[java] view plain copy
- static { class_init_native(); }
說明是在GpsLocationProvider中調用了class_init_native方法,進而說明GpsLocationProvider的reportLocation函數是GpsCallbacks的回調函數,即當Gps裝置的位置資訊發生變化時,它調用GpsLocationProvider的回調函數reportLocation,繼而調用LocationManagerService的reportLocation函數,進而更新應用層的位置資訊。
3 參考文章
基于android的GPS移植——主要結構體及接口介紹
androidGPS定位,定位城市稱,經緯度