閱讀613 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android係統Gps分析(一)

1 GPS架構



2 GPS分析

2.1 頭文件

頭文件定義在:hardware/libhardware/include/hardware/gps.h,定義了GPS底層相關的結構體和接口

  • GpsLocation

GPS位置信息結構體,包含經緯度,高度,速度,方位角等。


  1. /** Flags to indicate which values are valid in a GpsLocation. */  
  2. typedef uint16_t GpsLocationFlags;  
  3. // IMPORTANT: Note that the following values must match  
  4. // constants in GpsLocationProvider.java.  
  5. /** GpsLocation has valid latitude and longitude. */  
  6. #define GPS_LOCATION_HAS_LAT_LONG   0x0001  
  7. /** GpsLocation has valid altitude. */  
  8. #define GPS_LOCATION_HAS_ALTITUDE   0x0002  
  9. /** GpsLocation has valid speed. */  
  10. #define GPS_LOCATION_HAS_SPEED      0x0004  
  11. /** GpsLocation has valid bearing. */  
  12. #define GPS_LOCATION_HAS_BEARING    0x0008  
  13. /** GpsLocation has valid accuracy. */  
  14. #define GPS_LOCATION_HAS_ACCURACY   0x0010  
  15.   
  16. /** Represents a location. */  
  17. typedef struct {  
  18.     /** set to sizeof(GpsLocation) */  
  19.     size_t          size;  
  20.     /** Contains GpsLocationFlags bits. */  
  21.     uint16_t        flags;  
  22.     /** Represents latitude in degrees. */  
  23.     double          latitude;  
  24.     /** Represents longitude in degrees. */  
  25.     double          longitude;  
  26.     /** Represents altitude in meters above the WGS 84 reference 
  27.      * ellipsoid. */  
  28.     double          altitude;  
  29.     /** Represents speed in meters per second. */  
  30.     float           speed;  
  31.     /** Represents heading in degrees. */  
  32.     float           bearing;  
  33.     /** Represents expected accuracy in meters. */  
  34.     float           accuracy;  
  35.     /** Timestamp for the location fix. */  
  36.     GpsUtcTime      timestamp;  
  37. } GpsLocation;  

  • GpsStatus

GPS狀態包括5種狀態,分別為未知,正在定位,停止定位,啟動未定義,未啟動。


  1. /** GPS status event values. */  
  2. typedef uint16_t GpsStatusValue;  
  3. // IMPORTANT: Note that the following values must match  
  4. // constants in GpsLocationProvider.java.  
  5. /** GPS status unknown. */  
  6. #define GPS_STATUS_NONE             0  
  7. /** GPS has begun navigating. */  
  8. #define GPS_STATUS_SESSION_BEGIN    1  
  9. /** GPS has stopped navigating. */  
  10. #define GPS_STATUS_SESSION_END      2  
  11. /** GPS has powered on but is not navigating. */  
  12. #define GPS_STATUS_ENGINE_ON        3  
  13. /** GPS is powered off. */AgpsCallbacks  
  14.   
  15. AgpsInterface  
  16. #define GPS_STATUS_ENGINE_OFF       4  
  17.   
  18. /** Represents the status. */  
  19. typedef struct {  
  20.     /** set to sizeof(GpsStatus) */  
  21.     size_t          size;  
  22.     GpsStatusValue status;  
  23. } GpsStatus;  


  • GpsSvInfo

GPS衛星信息,包含衛星編號,信號強度,衛星仰望角,方位角等。

  1. /** Represents SV information. */  
  2. typedef struct {  
  3.     /** set to sizeof(GpsSvInfo) */  
  4.     size_t          size;  
  5.     /** Pseudo-random number for the SV. */  
  6.     int     prn;  
  7.     /** Signal to noise ratio. */  
  8.     float   snr;  
  9.     /** Elevation of SV in degrees. */  
  10.     float   elevation;  
  11.     /** Azimuth of SV in degrees. */  
  12.     float   azimuth;  
  13. } GpsSvInfo;  

  • GpsSvStatus

GPS衛星狀態,包含可見衛星數和信息,星曆時間,年曆時間等。


  1. /** Represents SV status. */  
  2. typedef struct {  
  3.     /** set to sizeof(GpsSvStatus) */  
  4.     size_t          size;  
  5.   
  6.     /** Number of SVs currently visible. */  
  7.     int         num_svs;  
  8.   
  9.     /** Contains an array of SV information. */  
  10.     GpsSvInfo   sv_list[GPS_MAX_SVS];  
  11.   
  12.     /** Represents a bit mask indicating which SVs 
  13.      * have ephemeris data. 
  14.      */  
  15.     uint32_t    ephemeris_mask;  
  16.   
  17.     /** Represents a bit mask indicating which SVs 
  18.      * have almanac data. 
  19.      */  
  20.     uint32_t    almanac_mask;  
  21.   
  22.     /** 
  23.      * Represents a bit mask indicating which SVs 
  24.      * were used for computing the most recent position fix. 
  25.      */  
  26.     uint32_t    used_in_fix_mask;  
  27. } GpsSvStatus;  

  • GpsCallbacks

回調函數定義

  1. /** Callback with location information. 向上層傳遞GPS位置信息 
  2.  *  Can only be called from a thread created by create_thread_cb. 
  3.  */  
  4. typedef void (* gps_location_callback)(GpsLocation* location);  
  5.   
  6. /** Callback with status information. 向上層傳遞GPS狀態信息 
  7.  *  Can only be called from a thread created by create_thread_cb. 
  8.  */  
  9. typedef void (* gps_status_callback)(GpsStatus* status);  
  10.   
  11. /** Callback with SV status information. 向上層傳遞GPS衛星信息 
  12.  *  Can only be called from a thread created by create_thread_cb. 
  13.  */  
  14. typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);  
  15.   
  16. /** Callback for reporting NMEA sentences. 向上層傳遞MEMA數據 
  17.  *  Can only be called from a thread created by create_thread_cb. 
  18.  */  
  19. typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);  
  20.   
  21. /** Callback to inform framework of the GPS engine's capabilities.告知GPS模塊可以實現的功能 
  22.  *  Capability parameter is a bit field of GPS_CAPABILITY_* flags. 
  23.  */  
  24. typedef void (* gps_set_capabilities)(uint32_t capabilities);  
  25.   
  26. /** Callback utility for acquiring the GPS wakelock.上鎖,防止處理GPS事件時中止。 
  27.  *  This can be used to prevent the CPU from suspending while handling GPS events. 
  28.  */  
  29. typedef void (* gps_acquire_wakelock)();  
  30.   
  31. /** Callback utility for releasing the GPS wakelock. */釋放鎖  
  32. typedef void (* gps_release_wakelock)();  
  33.   
  34. /** Callback for creating a thread that can call into the Java framework code.等待上層請求 
  35.  *  This must be used to create any threads that report events up to the framework. 
  36.  */  
  37. typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);  
  38.   
  39. /** GPS callback structure. */  
  40. typedef struct {  
  41.     /** set to sizeof(GpsCallbacks) */  
  42.     size_t      size;  
  43.     gps_location_callback location_cb;  
  44.     gps_status_callback status_cb;  
  45.     gps_sv_status_callback sv_status_cb;  
  46.     gps_nmea_callback nmea_cb;  
  47.     gps_set_capabilities set_capabilities_cb;  
  48.     gps_acquire_wakelock acquire_wakelock_cb;  
  49.     gps_release_wakelock release_wakelock_cb;  
  50.     gps_create_thread create_thread_cb;  
  51. } GpsCallbacks;  

  • GpsInterface

GPS接口是最重要的結構體,上層是通過此接口與硬件適配層交互的。


  1. /** Represents the standard GPS interface. */  
  2. typedef struct {  
  3.     /** set to sizeof(GpsInterface) */  
  4.     size_t          size;  
  5.     /** 
  6.      * Opens the interface and provides the callback routines 
  7.      * to the implemenation of this interface. 
  8.      */  
  9.     int   (*init)( GpsCallbacks* callbacks );  
  10.   
  11.     /** Starts navigating. 啟動定位*/  
  12.     int   (*start)( void );  
  13.   
  14.     /** Stops navigating. 取消定位*/  
  15.     int   (*stop)( void );  
  16.   
  17.     /** Closes the interface. 關閉GPS接口*/  
  18.     void  (*cleanup)( void );  
  19.   
  20.     /** Injects the current time.填入時間 */  
  21.     int   (*inject_time)(GpsUtcTime time, int64_t timeReference,  
  22.                          int uncertainty);  
  23.   
  24.     /** Injects current location from another location provider填入位置 
  25.      *  (typically cell ID). 
  26.      *  latitude and longitude are measured in degrees 
  27.      *  expected accuracy is measured in meters 
  28.      */  
  29.     int  (*inject_location)(double latitude, double longitude, float accuracy);  
  30.   
  31.     /** 
  32.      * Specifies that the next call to start will not use the刪除全部或部分輔助數據,在性能測試時使用 
  33.      * information defined in the flags. GPS_DELETE_ALL is passed for 
  34.      * a cold start. 
  35.      */  
  36.     void  (*delete_aiding_data)(GpsAidingData flags);  
  37.   
  38.     /**設置定位模式和GPS工作模式等 
  39.      * min_interval represents the time between fixes in milliseconds. 
  40.      * preferred_accuracy represents the requested fix accuracy in meters. 
  41.      * preferred_time represents the requested time to first fix in milliseconds. 
  42.      */  
  43.     int   (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,  
  44.             uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);  
  45.   
  46.     /** Get a pointer to extension information. 自定義的接口*/  
  47.     const void* (*get_extension)(const char* name);  
  48. } GpsInterface;  


  • gps_device_t

GPS設備結構體,繼承自hw_device_tcommon,硬件適配接口,向上層提供了重要的get_gps_interface接口。


  1. struct gps_device_t {  
  2.     struct hw_device_t common;  
  3.   
  4.     /** 
  5.      * Set the provided lights to the provided values. 
  6.      * 
  7.      * Returns: 0 on succes, error code on failure. 
  8.      */  
  9.     const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);  
  10. };  


2.2硬件適配層

GPS硬件適配層的源碼位於:hardware/qcom/gps目錄下。

我們看gps/loc_api/llibloc_api/gps.c,首先定義了gps設備模塊實例:

  1. const struct hw_module_t HAL_MODULE_INFO_SYM = {  
  2.     .tag = HARDWARE_MODULE_TAG,  
  3.     .version_major = 1,  
  4.     .version_minor = 0,  
  5.     .id = GPS_HARDWARE_MODULE_ID,  
  6.     .name = "loc_api GPS Module",  
  7.     .author = "Qualcomm USA, Inc.",  
  8.     .methods = &gps_module_methods,  
  9. };  

這裏的methods指向gps.c文件中的gps_module_methods


  1. static struct hw_module_methods_t gps_module_methods = {  
  2.     .open = open_gps  
  3. };  

gps_module_methods定義了設備的open函數為open_gps,我們看open_gps函數:


  1. static int open_gps(const struct hw_module_t* module, char const* name,  
  2.         struct hw_device_t** device)  
  3. {  
  4.     struct gps_device_t *dev = malloc(sizeof(struct gps_device_t));  
  5.     memset(dev, 0, sizeof(*dev));  
  6.   
  7.     dev->common.tag = HARDWARE_DEVICE_TAG;  
  8.     dev->common.version = 0;  
  9.     dev->common.module = (struct hw_module_t*)module;  
  10.     dev->get_gps_interface = gps__get_gps_interface;  
  11.   
  12.     *device = (struct hw_device_t*)dev;  
  13.     return 0;  
  14. }  

此處可以看作是GPS設備的初始化函數,在使用設備前必須執行此函數。函數裏麵指定了hw_device_tmodule成員,以及gps_device_tget_gps_interface成員。上層可通過gps_device_tget_gps_interface調用gps__get_gps_interface函數。gps__get_gps_interface的定義如下:

  1. const GpsInterface* gps__get_gps_interface(struct gps_device_t* dev)  
  2. {  
  3.     return get_gps_interface();  
  4. }  

用代碼跟蹤可看到,此函數返回了gps/loc_eng.cpp文件的sLocEngInterface變量,sLocEngInterface定義如下:

  1. // Defines the GpsInterface in gps.h  
  2. static const GpsInterface sLocEngInterface =  
  3. {  
  4.     sizeof(GpsInterface),  
  5.     loc_eng_init,  
  6.     loc_eng_start,  
  7.     loc_eng_stop,  
  8.     loc_eng_cleanup,  
  9.     loc_eng_inject_time,  
  10.     loc_eng_inject_location,  
  11.     loc_eng_delete_aiding_data,  
  12.     loc_eng_set_position_mode,  
  13.     loc_eng_get_extension,  
  14. };  

sLocEngInterface指定了GpsInterface結構體的各個回調函數,如啟動定位/取消定位等,這些回調函數的實現均在loc_eng.cpp中實現。



2.2 JNI適配層

GPSJNI適配層的源碼位於:frameworks/base/services/jni/com_android_server_location_GpsLocationProvider.cpp

首先看注冊JNI方法的函數定義:

[plain] view plaincopy
  1. int register_android_server_location_GpsLocationProvider(JNIEnv* env)  
  2. {  
  3.     return jniRegisterNativeMethods(env, "com/android/server/location/GpsLocationProvider", sMethods, NELEM(sMethods));  
  4. }  

此函數被同目錄下onload.cpp文件調用,調用地方在:

  1. extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)  
  2. {  
  3.     JNIEnv* env = NULL;  
  4.     jint result = -1;  
  5.   
  6.     if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {  
  7.         LOGE("GetEnv failed!");  
  8.         return result;  
  9.     }  
  10.     LOG_ASSERT(env, "Could not retrieve the env!");  
  11.   
  12.     //...省略其他注冊代碼  
  13.     register_android_server_location_GpsLocationProvider(env);  
  14.   
  15.     return JNI_VERSION_1_4;  
  16. }  

從這裏可以看到,JNI初始化的時候,即會進行JNI方法的注冊,從而使上層應用能通過JNI調用c/c++本地方法。

回到register_android_server_location_GpsLocationProvider函數,變量sMethods定義如下:

  1. static JNINativeMethod sMethods[] = {  
  2.      /* name, signature, funcPtr */  
  3.     {"class_init_native""()V", (void *)android_location_GpsLocationProvider_class_init_native},  
  4.     {"native_is_supported""()Z", (void*)android_location_GpsLocationProvider_is_supported},  
  5.     {"native_init""()Z", (void*)android_location_GpsLocationProvider_init},  
  6.     {"native_cleanup""()V", (void*)android_location_GpsLocationProvider_cleanup},  
  7.     {"native_set_position_mode""(IIIII)Z", (void*)android_location_GpsLocationProvider_set_position_mode},  
  8.     {"native_start""()Z", (void*)android_location_GpsLocationProvider_start},  
  9.     {"native_stop""()Z", (void*)android_location_GpsLocationProvider_stop},  
  10.     {"native_delete_aiding_data""(I)V", (void*)android_location_GpsLocationProvider_delete_aiding_data},  
  11.     {"native_read_sv_status""([I[F[F[F[I)I", (void*)android_location_GpsLocationProvider_read_sv_status},  
  12.     {"native_read_nmea""([BI)I", (void*)android_location_GpsLocationProvider_read_nmea},  
  13.     {"native_inject_time""(JJI)V", (void*)android_location_GpsLocationProvider_inject_time},  
  14.     {"native_inject_location""(DDF)V", (void*)android_location_GpsLocationProvider_inject_location},  
  15.     {"native_supports_xtra""()Z", (void*)android_location_GpsLocationProvider_supports_xtra},  
  16.     {"native_inject_xtra_data""([BI)V", (void*)android_location_GpsLocationProvider_inject_xtra_data},  
  17.     {"native_agps_data_conn_open""(Ljava/lang/String;)V", (void*)android_location_GpsLocationProvider_agps_data_conn_open},  
  18.     {"native_agps_data_conn_closed""()V", (void*)android_location_GpsLocationProvider_agps_data_conn_closed},  
  19.     {"native_agps_data_conn_failed""()V", (void*)android_location_GpsLocationProvider_agps_data_conn_failed},  
  20.     {"native_agps_set_id","(ILjava/lang/String;)V",(void*)android_location_GpsLocationProvider_agps_set_id},  
  21.     {"native_agps_set_ref_location_cellid","(IIIII)V",(void*)android_location_GpsLocationProvider_agps_set_reference_location_cellid},  
  22.     {"native_set_agps_server""(ILjava/lang/String;I)V", (void*)android_location_GpsLocationProvider_set_agps_server},  
  23.     {"native_send_ni_response""(II)V", (void*)android_location_GpsLocationProvider_send_ni_response},  
  24.     {"native_agps_ni_message""([BI)V", (void *)android_location_GpsLocationProvider_agps_send_ni_message},  
  25.     {"native_get_internal_state""()Ljava/lang/String;", (void*)android_location_GpsLocationProvider_get_internal_state},  
  26.     {"native_update_network_state""(ZIZLjava/lang/String;)V", (void*)android_location_GpsLocationProvider_update_network_state },  
  27. };  

這裏定義了GPS所有向上層提供的JNI本地方法,這些本地方法是如何與硬件適配層交互的呢?我們看其中一個本地方法android_location_GpsLocationProvider_start

  1. static jboolean android_location_GpsLocationProvider_start(JNIEnv* env, jobject obj)  
  2. {  
  3.     const GpsInterface* interface = GetGpsInterface(env, obj);  
  4.     if (interface)  
  5.         return (interface->start() == 0);  
  6.     else  
  7.         return false;  
  8. }  

它調用了GetGpsInterface獲得GpsInterface接口,然後直接調用該接口的start回調函數。GetGpsInterface方法定義如下:

  1. static const GpsInterface* GetGpsInterface(JNIEnv* env, jobject obj) {  
  2.     // this must be set before calling into the HAL library  
  3.     if (!mCallbacksObj)  
  4.         mCallbacksObj = env->NewGlobalRef(obj);  
  5.   
  6.     if (!sGpsInterface) {  
  7.         sGpsInterface = get_gps_interface();  
  8.         if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0) {  
  9.             sGpsInterface = NULL;  
  10.             return NULL;  
  11.         }  
  12.     }  
  13.     return sGpsInterface;  
  14. }  

這個函數返回了sGpsInterface,而sGpsInterface又是從get_gps_interface()獲得的,我們繼續查看get_gps_interface()函數的實現:

  1. static const GpsInterface* get_gps_interface() {  
  2.     int err;  
  3.     hw_module_t* module;  
  4.     const GpsInterface* interface = NULL;  
  5.   
  6.     err = hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);  
  7.     if (err == 0) {  
  8.         hw_device_t* device;  
  9.         err = module->methods->open(module, GPS_HARDWARE_MODULE_ID, &device);  
  10.         if (err == 0) {  
  11.             gps_device_t* gps_device = (gps_device_t *)device;  
  12.             interface = gps_device->get_gps_interface(gps_device);  
  13.         }  
  14.     }  
  15.   
  16.     return interface;  
  17. }  

這裏麵調用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

用於接收GpsNMEA數據

LocationListener

用於接收當位置信息發生變化時,LocationManager發出的通知



Address

地址信息類

Criteria

用於根據設備情況動態選擇provider

Geocoder

用於處理地理編碼信息

GpsSatellite

用於獲取當前衛星狀態

GpsStatus

用於獲取當前Gps狀態

Location

地理位置信息類

LocationManager

用於獲取和操作gps係統服務

LocationProvider

抽象類,用於提供位置提供者(Locationprovider



2.3.2 使用Gps編程接口

下麵,我們用一個代碼示例說明如何在應用層寫一個簡單的gps程序。

  • 首先在AndroidManifest.xml中添加位置服務權限:

[plain] view plaincopy
  1. <uses-permission android:name="android.permission.INTERNET" />     
  2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />     
  3. <uses-permission android:name="android.permission.ACCESS_FIND_LOCATION" />    
  4. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>    

  • 接著獲取位置信息:

[java] view plaincopy
  1.         //獲取位置服務  
  2.  LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);    
  3.        Criteria criteria = new Criteria();    
  4.        // 獲得最好的定位效果    
  5.        criteria.setAccuracy(Criteria.ACCURACY_FINE);  //設置為最大精度  
  6.        criteria.setAltitudeRequired(false);  //不獲取海拔信息  
  7.        criteria.setBearingRequired(false);  //不獲取方位信息  
  8.        criteria.setCostAllowed(false);  //是否允許付費  
  9.        criteria.setPowerRequirement(Criteria.POWER_LOW);  // 使用省電模式  
  10.        // 獲得當前的位置提供者    
  11.        String provider = locationManager.getBestProvider(criteria, true);    
  12.        // 獲得當前的位置    
  13.        Location location = locationManager.getLastKnownLocation(provider);    
  14. Geocoder gc = new Geocoder(this);     
  15.        List<Address> addresses = null;    
  16.        try {  
  17.     //根據經緯度獲得地址信息    
  18.            addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);    
  19.        } catch (IOException e) {    
  20.            e.printStackTrace();    
  21.        } if (addresses.size() > 0) {  
  22. //獲取address類的成員信息  
  23. Sring msg = “”;     
  24.        msg += "AddressLine:" + addresses.get(0).getAddressLine(0)+ "\n";     
  25.        msg += "CountryName:" + addresses.get(0).getCountryName()+ "\n";     
  26.        msg += "Locality:" + addresses.get(0).getLocality() + "\n";     
  27.        msg += "FeatureName:" + addresses.get(0).getFeatureName();     
  28.        }     

  • 設置偵聽,當位置信息發生變化時,自動更新相關信息

[java] view plaincopy
  1.       //匿名類,繼承自LocationListener接口  
  2. private final LocationListener locationListener = new LocationListener() {  
  3.            public void onLocationChanged(Location location) {  
  4.            updateWithNewLocation(location);//更新位置信息  
  5.            }  
  6.            public void onProviderDisabled(String provider){  
  7.            updateWithNewLocation(null);//更新位置信息  
  8.            }  
  9.            public void onProviderEnabled(String provider){ }  
  10.            public void onStatusChanged(String provider, int status,Bundle extras){ }  
  11.    };  
  12. //更新位置信息  
  13. private void updateWithNewLocation(Location location) {  
  14.          
  15.   
  16.            if (location != null) {  
  17.     //獲取經緯度  
  18.            double lat = location.getLatitude();  
  19.            double lng = location.getLongitude();  
  20.    }  
  21. //添加偵聽  
  22.  locationManager.requestLocationUpdates(provider, 200010,locationListener);  


2.3.3接口和類分析

下麵對相關的類或接口進行分析,LocationManager的代碼文件位於:frameworks/base/location/java/location/LocationManager.java 

我們看其構造函數:

[java] view plaincopy
  1. public LocationManager(ILocationManager service) {  
  2.         mService = service;  
  3.     }  

其中mServiceILocationManager接口類型,構造函數的參數為service,外部調用時傳入LocationManagerService實例。LocationManagerandroid係統的gps位置信息係統服務,在稍後將會對其進行分析。由帶參構造函數實例化LocationManager類的方式用得不多,一般用的方式是getSystemService獲得LocationManagerService服務,再強製轉換為LocationManager。例如在2.3.2中的代碼示例中是這樣獲取gps服務的:

[java] view plaincopy
  1. LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);    

這裏的Context.LOCATION_SERVICElocation”,標識gps服務。

LocationManagerService服務是整個GpsFramework的核心,首先看它是如何加載的,代碼文件位於:frameworks/base/services/java/com/android/server/systemserver.java

[java] view plaincopy
  1. //省略其他代碼  
  2. LocationManagerService location = null;  
  3. //省略其他代碼  
  4. try {  
  5.                 Slog.i(TAG, "Location Manager");  
  6.                 location = new LocationManagerService(context);  
  7.                 ServiceManager.addService(Context.LOCATION_SERVICE, location);  
  8.             } catch (Throwable e) {  
  9.                 Slog.e(TAG, "Failure starting Location Manager", e);  
  10.             }  

此處向ServiceManger係統服務管理器注冊了新的服務,其名稱為location”,類型為LocationManagerService。注冊此服務後,Java應用程序可通過ServiceManager獲得LocationManagerService的代理接口ILocationManager.Stub從而調用LocationManagerService提供的接口函數。ILocationManager位於:

frameworks/base/location/java/location/ILocationManager.aidl,其代碼如下:

[java] view plaincopy
  1. /** 
  2.  * System private API for talking with the location service. 
  3.  * 
  4.  * {@hide} 
  5.  */  
  6. interface ILocationManager  
  7. {  
  8.     List<String> getAllProviders();  
  9.     List<String> getProviders(in Criteria criteria, boolean enabledOnly);  
  10.     String getBestProvider(in Criteria criteria, boolean enabledOnly);  
  11.     boolean providerMeetsCriteria(String provider, in Criteria criteria);  
  12.   
  13.     void requestLocationUpdates(String provider, in Criteria criteria, long minTime, float minDistance,  
  14.         boolean singleShot, in ILocationListener listener);  
  15.     void requestLocationUpdatesPI(String provider, in Criteria criteria, long minTime, float minDistance,  
  16.         boolean singleShot, in PendingIntent intent);  
  17.     void removeUpdates(in ILocationListener listener);  
  18.     void removeUpdatesPI(in PendingIntent intent);  
  19.   
  20.     boolean addGpsStatusListener(IGpsStatusListener listener);  
  21.     void removeGpsStatusListener(IGpsStatusL

    最後更新:2017-04-03 12:55:57

      上一篇:go freopen重定向stdin與stdout後如何恢複正常
      下一篇:go Sql Server 常用命令小結