GPS源码


2 GPS分析
 
2.1 头文件
头文件定义在:hardware/libhardware/include/hardware/gps.h,定义了GPS底层相关的结构体和接口
•   GpsLocation
GPS位置信息结构体,包含经纬度,高度,速度,方位角等。
 
[cpp] view plaincopy 
2.  /** Flags to indicate which values are valid in a GpsLocation. */  
3.  typedef uint16_t GpsLocationFlags;  
4.  // IMPORTANT: Note that the following values must match  
5.  // constants in GpsLocationProvider.java.  
6.  /** GpsLocation has valid latitude and longitude. */  
7.  #define GPS_LOCATION_HAS_LAT_LONG   0x0001  
8.  /** GpsLocation has valid altitude. */  
9.  #define GPS_LOCATION_HAS_ALTITUDE   0x0002  
10. /** GpsLocation has valid speed. */  
11. #define GPS_LOCATION_HAS_SPEED      0x0004  
12. /** GpsLocation has valid bearing. */  
13. #define GPS_LOCATION_HAS_BEARING    0x0008  
14. /** GpsLocation has valid accuracy. */  
15. #define GPS_LOCATION_HAS_ACCURACY   0x0010  
16.   
17. /** Represents a location. */  
18. typedef struct {  
19.     /** set to sizeof(GpsLocation) */  
20.     size_t          size;  
21.     /** Contains GpsLocationFlags bits. */  
22.     uint16_t        flags;  
23.     /** Represents latitude in degrees. */  
24.     double          latitude;  
25.     /** Represents longitude in degrees. */  
26.     double          longitude;  
27.     /** Represents altitude in meters above the WGS 84 reference 
28.      * ellipsoid. */  
29.     double          altitude;  
30.     /** Represents speed in meters per second. */  
31.     float           speed;  
32.     /** Represents heading in degrees. */  
33.     float           bearing;  
34.     /** Represents expected accuracy in meters. */  
35.     float           accuracy;  
36.     /** Timestamp for the location fix. */  
37.     GpsUtcTime      timestamp;  
38. } GpsLocation;  

•   GpsStatus
GPS状态包括5种状态,分别为未知,正在定位,停止定位,启动未定义,未启动。
[cpp] view plaincopy 
40. /** GPS status event values. */  
41. typedef uint16_t GpsStatusValue;  
42. // IMPORTANT: Note that the following values must match  
43. // constants in GpsLocationProvider.java.  
44. /** GPS status unknown. */  
45. #define GPS_STATUS_NONE             0  
46. /** GPS has begun navigating. */  
47. #define GPS_STATUS_SESSION_BEGIN    1  
48. /** GPS has stopped navigating. */  
49. #define GPS_STATUS_SESSION_END      2  
50. /** GPS has powered on but is not navigating. */  
51. #define GPS_STATUS_ENGINE_ON        3  
52. /** GPS is powered off. */AgpsCallbacks  
53.   
54. AgpsInterface  
55. #define GPS_STATUS_ENGINE_OFF       4  
56.   
57. /** Represents the status. */  
58. typedef struct {  
59.     /** set to sizeof(GpsStatus) */  
60.     size_t          size;  
61.     GpsStatusValue status;  
62. } GpsStatus;  
 
 
•   GpsSvInfo
 
GPS卫星信息,包含卫星编号,信号强度,卫星仰望角,方位角等。
[cpp] view plaincopy 
64. /** Represents SV information. */  
65. typedef struct {  
66.     /** set to sizeof(GpsSvInfo) */  
67.     size_t          size;  
68.     /** Pseudo-random number for the SV. */  
69.     int     prn;  
70.     /** Signal to noise ratio. */  
71.     float   snr;  
72.     /** Elevation of SV in degrees. */  
73.     float   elevation;  
74.     /** Azimuth of SV in degrees. */  
75.     float   azimuth;  
76. } GpsSvInfo;  

•   GpsSvStatus
GPS卫星状态,包含可见卫星数和信息,星历时间,年历时间等。

 
[cpp] view plaincopy 
78. /** Represents SV status. */  
79. typedef struct {  
80.     /** set to sizeof(GpsSvStatus) */  
81.     size_t          size;  
82.   
83.     /** Number of SVs currently visible. */  
84.     int         num_svs;  
85.   
86.     /** Contains an array of SV information. */  
87.     GpsSvInfo   sv_list[GPS_MAX_SVS];  
88.   
89.     /** Represents a bit mask indicating which SVs 
90.      * have ephemeris data. 
91.      */  
92.     uint32_t    ephemeris_mask;  
93.   
94.     /** Represents a bit mask indicating which SVs 
95.      * have almanac data. 
96.      */  
97.     uint32_t    almanac_mask;  
98.   
99.     /** 
100.         * Represents a bit mask indicating which SVs 
101.         * were used for computing the most recent position fix. 
102.         */  
103.        uint32_t    used_in_fix_mask;  
104.    } GpsSvStatus;  

 
•   GpsCallbacks
 
回调函数定义
[cpp] view plaincopy 
106.    /** Callback with location information. 向上层传递GPS位置信息 
107.     *  Can only be called from a thread created by create_thread_cb. 
108.     */  
109.    typedef void (* gps_location_callback)(GpsLocation* location);  
110.      
111.    /** Callback with status information. 向上层传递GPS状态信息 
112.     *  Can only be called from a thread created by create_thread_cb. 
113.     */  
114.    typedef void (* gps_status_callback)(GpsStatus* status);  
115.      
116.    /** Callback with SV status information. 向上层传递GPS卫星信息 
117.     *  Can only be called from a thread created by create_thread_cb. 
118.     */  
119.    typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);  
120.      
121.    /** Callback for reporting NMEA sentences. 向上层传递MEMA数据 
122.     *  Can only be called from a thread created by create_thread_cb. 
123.     */  
124.    typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);  
125.      
126.    /** Callback to inform framework of the GPS engine's capabilities.告知GPS模块可以实现的功能 
127.     *  Capability parameter is a bit field of GPS_CAPABILITY_* flags. 
128.     */  
129.    typedef void (* gps_set_capabilities)(uint32_t capabilities);  
130.      
131.    /** Callback utility for acquiring the GPS wakelock.上锁,防止处理GPS事件时中止。 
132.     *  This can be used to prevent the CPU from suspending while handling GPS events. 
133.     */  
134.    typedef void (* gps_acquire_wakelock)();  
135.      
136.    /** Callback utility for releasing the GPS wakelock. */释放锁  
137.    typedef void (* gps_release_wakelock)();  
138.      
139.    /** Callback for creating a thread that can call into the Java framework code.等待上层请求 
140.     *  This must be used to create any threads that report events up to the framework. 
141.     */  
142.    typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);  
143.      
144.    /** GPS callback structure. */  
145.    typedef struct {  
146.        /** set to sizeof(GpsCallbacks) */  
147.        size_t      size;  
148.        gps_location_callback location_cb;  
149.        gps_status_callback status_cb;  
150.        gps_sv_status_callback sv_status_cb;  
151.        gps_nmea_callback nmea_cb;  
152.        gps_set_capabilities set_capabilities_cb;  
153.        gps_acquire_wakelock acquire_wakelock_cb;  
154.        gps_release_wakelock release_wakelock_cb;  
155.        gps_create_thread create_thread_cb;  
156.    } GpsCallbacks;  

•   GpsInterface
GPS接口是最重要的结构体,上层是通过此接口与硬件适配层交互的。

 
[cpp] view plaincopy 
158.    /** Represents the standard GPS interface. */  
159.    typedef struct {  
160.        /** set to sizeof(GpsInterface) */  
161.        size_t          size;  
162.        /** 
163.         * Opens the interface and provides the callback routines 
164.         * to the implemenation of this interface. 
165.         */  
166.        int   (*init)( GpsCallbacks* callbacks );  
167.      
168.        /** Starts navigating. 启动定位*/  
169.        int   (*start)( void );  
170.      
171.        /** Stops navigating. 取消定位*/  
172.        int   (*stop)( void );  
173.      
174.        /** Closes the interface. 关闭GPS接口*/  
175.        void  (*cleanup)( void );  
176.      
177.        /** Injects the current time.填入时间 */  
178.        int   (*inject_time)(GpsUtcTime time, int64_t timeReference,  
179.                             int uncertainty);  
180.      
181.        /** Injects current location from another location provider填入位置 
182.         *  (typically cell ID). 
183.         *  latitude and longitude are measured in degrees 
184.         *  expected accuracy is measured in meters 
185.         */  
186.        int  (*inject_location)(double latitude, double longitude, float accuracy);  
187.      
188.        /** 
189.         * Specifies that the next call to start will not use the删除全部或部分辅助数据,在性能测试时使用 
190.         * information defined in the flags. GPS_DELETE_ALL is passed for 
191.         * a cold start. 
192.         */  
193.        void  (*delete_aiding_data)(GpsAidingData flags);  
194.      
195.        /**设置定位模式和GPS工作模式等 
196.         * min_interval represents the time between fixes in milliseconds. 
197.         * preferred_accuracy represents the requested fix accuracy in meters. 
198.         * preferred_time represents the requested time to first fix in milliseconds. 
199.         */  
200.        int   (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,  
201.                uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);  
202.      
203.        /** Get a pointer to extension information. 自定义的接口*/  
204.        const void* (*get_extension)(const char* name);  
205.    } GpsInterface;  
 
 
 
•   gps_device_t
 
GPS设备结构体,继承自hw_device_tcommon,硬件适配接口,向上层提供了重要的get_gps_interface接口。

[cpp] view plaincopy 
207.    struct gps_device_t {  
208.        struct hw_device_t common;  
209.      
210.        /** 
211.         * Set the provided lights to the provided values. 
212.         * 
213.         * Returns: 0 on succes, error code on failure. 
214.         */  
215.        const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);  
216.    };  

 
2.2硬件适配层
 
GPS硬件适配层的源码位于:hardware/qcom/gps目录下。
我们看gps/loc_api/llibloc_api/gps.c,首先定义了gps设备模块实例:
[cpp] view plaincopy 
217.    const struct hw_module_t HAL_MODULE_INFO_SYM = {  
218.        .tag = HARDWARE_MODULE_TAG,  
219.        .version_major = 1,  
220.        .version_minor = 0,  
221.        .id = GPS_HARDWARE_MODULE_ID,  
222.        .name = "loc_api GPS Module",  
223.        .author = "Qualcomm USA, Inc.",  
224.        .methods = &gps_module_methods,  
225.    };  

这里的methods指向gps.c文件中的gps_module_methods

 
[cpp] view plaincopy 
226.    static struct hw_module_methods_t gps_module_methods = {  
227.        .open = open_gps  
228.    };  

 
gps_module_methods定义了设备的open函数为open_gps,我们看open_gps函数:

 
[cpp] view plaincopy 
229.    static int open_gps(const struct hw_module_t* module, char const* name,  
230.            struct hw_device_t** device)  
231.    {  
232.        struct gps_device_t *dev = malloc(sizeof(struct gps_device_t));  
233.        memset(dev, 0, sizeof(*dev));  
234.      
235.        dev->common.tag = HARDWARE_DEVICE_TAG;  
236.        dev->common.version = 0;  
237.        dev->common.module = (struct hw_module_t*)module;  
238.        dev->get_gps_interface = gps__get_gps_interface;  
239.      
240.        *device = (struct hw_device_t*)dev;  
241.        return 0;  
242.    }  

 
此处可以看作是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 plaincopy 
243.    const GpsInterface* gps__get_gps_interface(struct gps_device_t* dev)  
244.    {  
245.        return get_gps_interface();  
246.    }  

用代码跟踪可看到,此函数返回了gps/loc_eng.cpp文件的sLocEngInterface变量,sLocEngInterface定义如下:
[cpp] view plaincopy 
247.    // Defines the GpsInterface in gps.h  
248.    static const GpsInterface sLocEngInterface =  
249.    {  
250.        sizeof(GpsInterface),  
251.        loc_eng_init,  
252.        loc_eng_start,  
253.        loc_eng_stop,  
254.        loc_eng_cleanup,  
255.        loc_eng_inject_time,  
256.        loc_eng_inject_location,  
257.        loc_eng_delete_aiding_data,  
258.        loc_eng_set_position_mode,  
259.        loc_eng_get_extension,  
260.    };  

sLocEngInterface指定了GpsInterface结构体的各个回调函数,如启动定位/取消定位等,这些回调函数的实现均在loc_eng.cpp中实现。

 
 
2.2 JNI适配层
 
GPSJNI适配层的源码位于:frameworks/base/services/jni/com_android_server_location_GpsLocationProvider.cpp
首先看注册JNI方法的函数定义:
[plain] view plaincopy 
261.    int register_android_server_location_GpsLocationProvider(JNIEnv* env)  
262.    {  
263.        return jniRegisterNativeMethods(env, "com/android/server/location/GpsLocationProvider", sMethods, NELEM(sMethods));  
264.    }  

此函数被同目录下onload.cpp文件调用,调用地方在:
[cpp] view plaincopy 
265.    extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)  
266.    {  
267.        JNIEnv* env = NULL;  
268.        jint result = -1;  
269.      
270.        if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {  
271.            LOGE("GetEnv failed!");  
272.            return result;  
273.        }  
274.        LOG_ASSERT(env, "Could not retrieve the env!");  
275.      
276.        //...省略其他注册代码  
277.        register_android_server_location_GpsLocationProvider(env);  
278.      
279.        return JNI_VERSION_1_4;  
280.    }  

从这里可以看到,JNI初始化的时候,即会进行JNI方法的注册,从而使上层应用能通过JNI调用c/c++本地方法。
回到register_android_server_location_GpsLocationProvider函数,变量sMethods定义如下:
[cpp] view plaincopy 
281.    static JNINativeMethod sMethods[] = {  
282.         /* name, signature, funcPtr */  
283.        {"class_init_native", "()V", (void *)android_location_GpsLocationProvider_class_init_native},  
284.        {"native_is_supported", "()Z", (void*)android_location_GpsLocationProvider_is_supported},  
285.        {"native_init", "()Z", (void*)android_location_GpsLocationProvider_init},  
286.        {"native_cleanup", "()V", (void*)android_location_GpsLocationProvider_cleanup},  
287.        {"native_set_position_mode", "(IIIII)Z", (void*)android_location_GpsLocationProvider_set_position_mode},  
288.        {"native_start", "()Z", (void*)android_location_GpsLocationProvider_start},  
289.        {"native_stop", "()Z", (void*)android_location_GpsLocationProvider_stop},  
290.        {"native_delete_aiding_data", "(I)V", (void*)android_location_GpsLocationProvider_delete_aiding_data},  
291.        {"native_read_sv_status", "([I[F[F[F[I)I", (void*)android_location_GpsLocationProvider_read_sv_status},  
292.        {"native_read_nmea", "([BI)I", (void*)android_location_GpsLocationProvider_read_nmea},  
293.        {"native_inject_time", "(JJI)V", (void*)android_location_GpsLocationProvider_inject_time},  
294.        {"native_inject_location", "(DDF)V", (void*)android_location_GpsLocationProvider_inject_location},  
295.        {"native_supports_xtra", "()Z", (void*)android_location_GpsLocationProvider_supports_xtra},  
296.        {"native_inject_xtra_data", "([BI)V", (void*)android_location_GpsLocationProvider_inject_xtra_data},  
297.        {"native_agps_data_conn_open", "(Ljava/lang/String;)V", (void*)android_location_GpsLocationProvider_agps_data_conn_open},  
298.        {"native_agps_data_conn_closed", "()V", (void*)android_location_GpsLocationProvider_agps_data_conn_closed},  
299.        {"native_agps_data_conn_failed", "()V", (void*)android_location_GpsLocationProvider_agps_data_conn_failed},  
300.        {"native_agps_set_id","(ILjava/lang/String;)V",(void*)android_location_GpsLocationProvider_agps_set_id},  
301.        {"native_agps_set_ref_location_cellid","(IIIII)V",(void*)android_location_GpsLocationProvider_agps_set_reference_location_cellid},  
302.        {"native_set_agps_server", "(ILjava/lang/String;I)V", (void*)android_location_GpsLocationProvider_set_agps_server},  
303.        {"native_send_ni_response", "(II)V", (void*)android_location_GpsLocationProvider_send_ni_response},  
304.        {"native_agps_ni_message", "([BI)V", (void *)android_location_GpsLocationProvider_agps_send_ni_message},  
305.        {"native_get_internal_state", "()Ljava/lang/String;", (void*)android_location_GpsLocationProvider_get_internal_state},  
306.        {"native_update_network_state", "(ZIZLjava/lang/String;)V", (void*)android_location_GpsLocationProvider_update_network_state },  
307.    };  

这里定义了GPS所有向上层提供的JNI本地方法,这些本地方法是如何与硬件适配层交互的呢?我们看其中一个本地方法android_location_GpsLocationProvider_start:
[cpp] view plaincopy 
308.    static jboolean android_location_GpsLocationProvider_start(JNIEnv* env, jobject obj)  
309.    {  
310.        const GpsInterface* interface = GetGpsInterface(env, obj);  
311.        if (interface)  
312.            return (interface->start() == 0);  
313.        else  
314.            return false;  
315.    }  

它调用了GetGpsInterface获得GpsInterface接口,然后直接调用该接口的start回调函数。GetGpsInterface方法定义如下:
[cpp] view plaincopy 
316.    static const GpsInterface* GetGpsInterface(JNIEnv* env, jobject obj) {  
317.        // this must be set before calling into the HAL library  
318.        if (!mCallbacksObj)  
319.            mCallbacksObj = env->NewGlobalRef(obj);  
320.      
321.        if (!sGpsInterface) {  
322.            sGpsInterface = get_gps_interface();  
323.            if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0) {  
324.                sGpsInterface = NULL;  
325.                return NULL;  
326.            }  
327.        }  
328.        return sGpsInterface;  
329.    }  

这个函数返回了sGpsInterface,而sGpsInterface又是从get_gps_interface()获得的,我们继续查看get_gps_interface()函数的实现:
[cpp] view plaincopy 
330.    static const GpsInterface* get_gps_interface() {  
331.        int err;  
332.        hw_module_t* module;  
333.        const GpsInterface* interface = NULL;  
334.      
335.        err = hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);  
336.        if (err == 0) {  
337.            hw_device_t* device;  
338.            err = module->methods->open(module, GPS_HARDWARE_MODULE_ID, &device);  
339.            if (err == 0) {  
340.                gps_device_t* gps_device = (gps_device_t *)device;  
341.                interface = gps_device->get_gps_interface(gps_device);  
342.            }  
343.        }  
344.      
345.        return interface;  
346.    }  

这里面调用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 plaincopy 
350.         
351.         
352.        
353.        

•   接着获取位置信息:
[java] view plaincopy 
355.            //获取位置服务  
356.     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);    
357.           Criteria criteria = new Criteria();    
358.           // 获得最好的定位效果    
359.           criteria.setAccuracy(Criteria.ACCURACY_FINE);  //设置为最大精度  
360.           criteria.setAltitudeRequired(false);  //不获取海拔信息  
361.           criteria.setBearingRequired(false);  //不获取方位信息  
362.           criteria.setCostAllowed(false);  //是否允许付费  
363.           criteria.setPowerRequirement(Criteria.POWER_LOW);  // 使用省电模式  
364.           // 获得当前的位置提供者    
365.           String provider = locationManager.getBestProvider(criteria, true);    
366.           // 获得当前的位置    
367.           Location location = locationManager.getLastKnownLocation(provider);    
368.    Geocoder gc = new Geocoder(this);     
369.           List
addresses = null; 370. try { 371. //根据经纬度获得地址信息 372. addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 373. } catch (IOException e) { 374. e.printStackTrace(); 375. } if (addresses.size() > 0) { 376. //获取address类的成员信息 377. Sring msg = “”; 378. msg += "AddressLine:" + addresses.get(0).getAddressLine(0)+ "\n"; 379. msg += "CountryName:" + addresses.get(0).getCountryName()+ "\n"; 380. msg += "Locality:" + addresses.get(0).getLocality() + "\n"; 381. msg += "FeatureName:" + addresses.get(0).getFeatureName(); 382. } • 设置侦听,当位置信息发生变化时,自动更新相关信息 [java] view plaincopy 384. //匿名类,继承自LocationListener接口 385. private final LocationListener locationListener = new LocationListener() { 386. public void onLocationChanged(Location location) { 387. updateWithNewLocation(location);//更新位置信息 388. } 389. public void onProviderDisabled(String provider){ 390. updateWithNewLocation(null);//更新位置信息 391. } 392. public void onProviderEnabled(String provider){ } 393. public void onStatusChanged(String provider, int status,Bundle extras){ } 394. }; 395. //更新位置信息 396. private void updateWithNewLocation(Location location) { 397. 398. 399. if (location != null) { 400. //获取经纬度 401. double lat = location.getLatitude(); 402. double lng = location.getLongitude(); 403. } 404. //添加侦听 405. locationManager.requestLocationUpdates(provider, 2000, 10,locationListener); 2.3.3接口和类分析 下面对相关的类或接口进行分析,LocationManager的代码文件位于:frameworks/base/location/java/location/LocationManager.java 我们看其构造函数: [java] view plaincopy 406. public LocationManager(ILocationManager service) { 407. mService = service; 408. } 其中mService为ILocationManager接口类型,构造函数的参数为service,外部调用时传入LocationManagerService实例。LocationManager是android系统的gps位置信息系统服务,在稍后将会对其进行分析。由带参构造函数实例化LocationManager类的方式用得不多,一般用的方式是由getSystemService获得LocationManagerService服务,再强制转换为LocationManager。例如在2.3.2中的代码示例中是这样获取gps服务的: [java] view plaincopy 409. 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 plaincopy 410. …//省略其他代码 411. LocationManagerService location = null; 412. …//省略其他代码 413. try { 414. Slog.i(TAG, "Location Manager"); 415. location = new LocationManagerService(context); 416. ServiceManager.addService(Context.LOCATION_SERVICE, location); 417. } catch (Throwable e) { 418. Slog.e(TAG, "Failure starting Location Manager", e); 419. } 此处向ServiceManger系统服务管理器注册了新的服务,其名称为”location”,类型为LocationManagerService。注册此服务后,Java应用程序可通过ServiceManager获得LocationManagerService的代理接口ILocationManager.Stub,从而调用LocationManagerService提供的接口函数。ILocationManager位于: frameworks/base/location/java/location/ILocationManager.aidl,其代码如下: [java] view plaincopy 420. /** 421. * System private API for talking with the location service. 422. * 423. * {@hide} 424. */ 425. interface ILocationManager 426. { 427. List getAllProviders(); 428. List getProviders(in Criteria criteria, boolean enabledOnly); 429. String getBestProvider(in Criteria criteria, boolean enabledOnly); 430. boolean providerMeetsCriteria(String provider, in Criteria criteria); 431. 432. void requestLocationUpdates(String provider, in Criteria criteria, long minTime, float minDistance, 433. boolean singleShot, in ILocationListener listener); 434. void requestLocationUpdatesPI(String provider, in Criteria criteria, long minTime, float minDistance, 435. boolean singleShot, in PendingIntent intent); 436. void removeUpdates(in ILocationListener listener); 437. void removeUpdatesPI(in PendingIntent intent); 438. 439. boolean addGpsStatusListener(IGpsStatusListener listener); 440. void removeGpsStatusListener(IGpsStatusListener listener); 441. 442. // for reporting callback completion 443. void locationCallbackFinished(ILocationListener listener); 444. 445. boolean sendExtraCommand(String provider, String command, inout Bundle extras); 446. 447. void addProximityAlert(double latitude, double longitude, float distance, 448. long expiration, in PendingIntent intent); 449. void removeProximityAlert(in PendingIntent intent); 450. 451. Bundle getProviderInfo(String provider); 452. boolean isProviderEnabled(String provider); 453. 454. Location getLastKnownLocation(String provider); 455. 456. // Used by location providers to tell the location manager when it has a new location. 457. // Passive is true if the location is coming from the passive provider, in which case 458. // it need not be shared with other providers. 459. void reportLocation(in Location location, boolean passive); 460. 461. boolean geocoderIsPresent(); 462. String getFromLocation(double latitude, double longitude, int maxResults, 463. in GeocoderParams params, out List
addrs); 464. String getFromLocationName(String locationName, 465. double lowerLeftLatitude, double lowerLeftLongitude, 466. double upperRightLatitude, double upperRightLongitude, int maxResults, 467. in GeocoderParams params, out List
addrs); 468. 469. void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite, 470. boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude, 471. boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy); 472. void removeTestProvider(String provider); 473. void setTestProviderLocation(String provider, in Location loc); 474. void clearTestProviderLocation(String provider); 475. void setTestProviderEnabled(String provider, boolean enabled); 476. void clearTestProviderEnabled(String provider); 477. void setTestProviderStatus(String provider, int status, in Bundle extras, long updateTime); 478. void clearTestProviderStatus(String provider); 479. 480. // for NI support 481. boolean sendNiResponse(int notifId, int userResponse); 482. } android系统通过ILocationManager.aidl文件自动生成IlocationManager.Stub代理接口,在Java客户端获取LocationManagerService的方式如下: [java] view plaincopy 483. ILocationManager mLocationManager; 484. IBinder b = ServiceManager.getService(Context.LOCATION_SERVICE); 485. 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 plaincopy 486. void systemReady() { 487. // we defer starting up the service until the system is ready 488. Thread thread = new Thread(null, this, "LocationManagerService"); 489. thread.start(); 490. } 此处启动自身服务线程,因LocationMangerService继承自Runnable接口,当启动此线程后,会执行继承自Runnable接口的run()函数,我们看run()函数的定义: [java] view plaincopy 491. public void run() 492. { 493. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 494. Looper.prepare(); 495. mLocationHandler = new LocationWorkerHandler(); 496. initialize(); 497. Looper.loop(); 498. } 此处调用了initialize()进行初始化,initialize()函数定义如下: [java] view plaincopy 499. private void initialize() { 500. //...省略其他代码 501. loadProviders(); 502. 503. //...省略其他代码 504. 505. } 此处调用了loadProviders()函数,loadProviders()函数调用了_loadProvidersLocked(),其代码如下: [java] view plaincopy 506. private void _loadProvidersLocked() { 507. // Attempt to load "real" providers first 508. if (GpsLocationProvider.isSupported()) { 509. // Create a gps location provider 510. GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this); 511. mGpsStatusProvider = gpsProvider.getGpsStatusProvider(); 512. mNetInitiatedListener = gpsProvider.getNetInitiatedListener(); 513. addProvider(gpsProvider); 514. mGpsLocationProvider = gpsProvider; 515. } 516. 517. // create a passive location provider, which is always enabled 518. PassiveProvider passiveProvider = new PassiveProvider(this); 519. addProvider(passiveProvider); 520. mEnabledProviders.add(passiveProvider.getName()); 521. 522. // initialize external network location and geocoder services 523. if (mNetworkLocationProviderPackageName != null) { 524. mNetworkLocationProvider = 525. new LocationProviderProxy(mContext, LocationManager.NETWORK_PROVIDER, 526. mNetworkLocationProviderPackageName, mLocationHandler); 527. addProvider(mNetworkLocationProvider); 528. } 529. 530. if (mGeocodeProviderPackageName != null) { 531. mGeocodeProvider = new GeocoderProxy(mContext, mGeocodeProviderPackageName); 532. } 533. 534. updateProvidersLocked(); 535. } 在这里对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 plaincopy 536. // 获得当前的位置提供者 537. String provider = locationManager.getBestProvider(criteria, true); getBestProvider其实是根据Criteria的条件遍历mProviders集合,返回符合条件的provider名称。我们再看GpsLocationProvider的实现,其代码文件位于: frameworks/base/services/java/com/android/server/location/GpsLocationProvider.java 在GpsLocationProvider的构造函数中: [plain] view plaincopy 538. public GpsLocationProvider(Context context, ILocationManager locationManager) { 539. 540. //...省略部分代码 541. IntentFilter intentFilter = new IntentFilter(); 542. intentFilter.addAction(Intents.DATA_SMS_RECEIVED_ACTION); 543. intentFilter.addDataScheme("sms"); 544. intentFilter.addDataAuthority("localhost","7275"); 545. context.registerReceiver(mBroadcastReciever, intentFilter); 546. 547. intentFilter = new IntentFilter(); 548. intentFilter.addAction(Intents.WAP_PUSH_RECEIVED_ACTION); 549. try { 550. intentFilter.addDataType("application/vnd.omaloc-supl-init"); 551. } catch (IntentFilter.MalformedMimeTypeException e) { 552. Log.w(TAG, "Malformed SUPL init mime type"); 553. } 554. context.registerReceiver(mBroadcastReciever, intentFilter); 555. 556. 557. //...省略部分代码 558. // wait until we are fully initialized before returning 559. mThread = new GpsLocationProviderThread(); 560. mThread.start(); 561. while (true) { 562. try { 563. mInitializedLatch.await(); 564. break; 565. } catch (InterruptedException e) { 566. Thread.currentThread().interrupt(); 567. } 568. } 569. } 这里注册了广播接受者mBroadcastReciever,用于接收广播消息,消息过滤在intentFilter中定义。下面看它接收广播消息时的动作: [java] view plaincopy 570. private final BroadcastReceiver mBroadcastReciever = new BroadcastReceiver() { 571. @Override public void onReceive(Context context, Intent intent) { 572. String action = intent.getAction(); 573. 574. if (action.equals(ALARM_WAKEUP)) { 575. if (DEBUG) Log.d(TAG, "ALARM_WAKEUP"); 576. startNavigating(false); 577. } else if (action.equals(ALARM_TIMEOUT)) { 578. if (DEBUG) Log.d(TAG, "ALARM_TIMEOUT"); 579. hibernate(); 580. } else if (action.equals(Intents.DATA_SMS_RECEIVED_ACTION)) { 581. checkSmsSuplInit(intent); 582. } else if (action.equals(Intents.WAP_PUSH_RECEIVED_ACTION)) { 583. checkWapSuplInit(intent); 584. } 585. } 586. }; 当接收ALARM_EAKEUP时,执行startNavigating函数,当接收到ALARM_TIMEOUT广播时,执行hibernate函数。这两个函数很关键,下面看他们的实现: [java] view plaincopy 587. private void startNavigating(boolean singleShot) { 588. 589. //...省略部分代码 590. 591. if (!native_set_position_mode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC, 592. interval, 0, 0)) { 593. mStarted = false; 594. Log.e(TAG, "set_position_mode failed in startNavigating()"); 595. return; 596. } 597. if (!native_start()) { 598. mStarted = false; 599. Log.e(TAG, "native_start failed in startNavigating()"); 600. return; 601. } 602. //...省略部分代码 603. } 看到没有,这里调用了native_set_position_mode和native_start方法,而这些方法正是我们之前在JNI适配层提到的注册的本地方法。同样的,hibernate函数调用了JNI提供的native_stop方法。我们再看GpsLocationProvider的内部私有函数: ![1.png](https://upload-images.jianshu.io/upload_images/15042138-a032f3f667e9f906.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 可以看到所有这些本地方法,都是在JNI层注册的,GpsLocationProvider类是从JNI层到Framework层的通道。 下面回到LocationManagerService,分析如何获取最新的位置信息(Location),获取最新的location的函数是getLastKnownLocation,其实现如下: [java] view plaincopy 604. private Location _getLastKnownLocationLocked(String provider) { 605. checkPermissionsSafe(provider); 606. 607. LocationProviderInterface p = mProvidersByName.get(provider); 608. if (p == null) { 609. return null; 610. } 611. 612. if (!isAllowedBySettingsLocked(provider)) { 613. return null; 614. } 615. 616. return mLastKnownLocation.get(provider); 617. } 这里mLastKnownLocation类型为HashMap,所以mLastKnownLocation.get(provider)表示通过provider的名称在哈希字典中获取相应的location,那么这些location是什么时候被存入到哈希字典中的呢? 我们回到LocationManagerService的run函数: [java] view plaincopy 618. public void run() 619. { 620. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 621. Looper.prepare(); 622. mLocationHandler = new LocationWorkerHandler(); 623. initialize(); 624. Looper.loop(); 625. } 这里对类型为LocationWorkerHandler的变量进行初始化,LocationWorkerHandler是在LocationManagerService的一个内部类,它继承自Handler类,Handler是Android系统用于应用程序内部通信的组件,内部通信指同个进程的主线程与其他线程间的通信,Handler通过Message或Runnable对象进行通信。我们继续看LocationWorkerHandler的实现: [java] view plaincopy 626. private class LocationWorkerHandler extends Handler { 627. 628. @Override 629. public void handleMessage(Message msg) { 630. try { 631. if (msg.what == MESSAGE_LOCATION_CHANGED) { 632. // log("LocationWorkerHandler: MESSAGE_LOCATION_CHANGED!"); 633. 634. synchronized (mLock) { 635. Location location = (Location) msg.obj; 636. String provider = location.getProvider(); 637. boolean passive = (msg.arg1 == 1); 638. 639. if (!passive) { 640. // notify other providers of the new location 641. for (int i = mProviders.size() - 1; i >= 0; i--) { 642. LocationProviderInterface p = mProviders.get(i); 643. if (!provider.equals(p.getName())) { 644. p.updateLocation(location); 645. } 646. } 647. } 648. 649. if (isAllowedBySettingsLocked(provider)) { 650. handleLocationChangedLocked(location, passive); 651. } 652. } 653. } else if (msg.what == MESSAGE_PACKAGE_UPDATED) { 654. //...省略部分代码 655. } 656. } 657. } catch (Exception e) { 658. // Log, don't crash! 659. Slog.e(TAG, "Exception in LocationWorkerHandler.handleMessage:", e); 660. } 661. } 662. } 这里重写Handle类的handleMessage方法,处理用Handle接收的Message对象消息。当接受到位置信息变化的消息MESSAGE_LOCATION_CHANGED时,调用p.updateLocationhandleLocationChangedLocked方法,其实现如下: [java] view plaincopy 663. private void handleLocationChangedLocked(Location location, boolean passive) { 664. //...省略部分代码 665. 666. // Update last known location for provider 667. Location lastLocation = mLastKnownLocation.get(provider); 668. if (lastLocation == null) { 669. mLastKnownLocation.put(provider, new Location(location)); 670. } else { 671. lastLocation.set(location); 672. } 673. //...省略部分代码 674. } 可以看到是在handleLocationChangedLocked函数中实现对lastknownlocation的更新的,那么在LocationWorkerHandler类中处理的MESSAGE_LOCATION_CHANGED消息是谁发送出来的呢?答案是在LocationManagerService类的reportLocation函数中: [java] view plaincopy 675. public void reportLocation(Location location, boolean passive) { 676. if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER) 677. != PackageManager.PERMISSION_GRANTED) { 678. throw new SecurityException("Requires INSTALL_LOCATION_PROVIDER permission"); 679. } 680. 681. mLocationHandler.removeMessages(MESSAGE_LOCATION_CHANGED, location); 682. Message m = Message.obtain(mLocationHandler, MESSAGE_LOCATION_CHANGED, location); 683. m.arg1 = (passive ? 1 : 0); 684. mLocationHandler.sendMessageAtFrontOfQueue(m); 685. } 此处构造了新的Message对象,然后发送到消息队列的首位置。在GpsLocationProvider类的reportLocation函数中,有这样一段代码: [java] view plaincopy 686. try { 687. mLocationManager.reportLocation(mLocation, false); 688. } catch (RemoteException e) { 689. Log.e(TAG, "RemoteException calling reportLocation"); 690. } 所以实际是由GpsLocationProvider主动调用LocationManagerService的reportLocation方法,从而更新最新的位置信息。 实际上,GpsLocationoProvider的reportLocation对应了硬件适配层中的GpsCallbacks结构体中的回调函数gps_location_callback [cpp] view plaincopy 691. /** Callback with location information. 向上层传递GPS位置信息 692. * Can only be called from a thread created by create_thread_cb. 693. */ 694. 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 plaincopy 695. static const GpsInterface* GetGpsInterface(JNIEnv* env, jobject obj) { 696. // this must be set before calling into the HAL library 697. if (!mCallbacksObj) 698. mCallbacksObj = env->NewGlobalRef(obj); 699. 700. if (!sGpsInterface) { 701. sGpsInterface = get_gps_interface(); 702. if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0) { 703. sGpsInterface = NULL; 704. return NULL; 705. } 706. } 707. return sGpsInterface; 708. } 这里面的sGpsInterface->init(&sGpsCallbacks)调用了GpsInterface的init回调函数,即初始化GpsCallbacks结构体变量sGpsCallbacks,sGpsCallbacks定义如下: [cpp] view plaincopy 709. GpsCallbacks sGpsCallbacks = { 710. sizeof(GpsCallbacks), 711. location_callback, 712. status_callback, 713. sv_status_callback, 714. nmea_callback, 715. set_capabilities_callback, 716. acquire_wakelock_callback, 717. release_wakelock_callback, 718. create_thread_callback, 719. }; 我们再次看GpsCallbacks的定义(其代码文件在硬件适配层的头文件gps.h中): [cpp] view plaincopy 720. typedef struct { 721. size_t size; 722. gps_location_callback location_cb; 723. gps_status_callback status_cb; 724. gps_sv_status_callback sv_status_cb; 725. gps_nmea_callback nmea_cb; 726. gps_set_capabilities set_capabilities_cb; 727. gps_acquire_wakelock acquire_wakelock_cb; 728. gps_release_wakelock release_wakelock_cb; 729. gps_create_thread create_thread_cb; 730. } GpsCallbacks; 比较sGpsCallbacks与GpsCallbacks,可以看到location_callback与gps_location_callback对应。再看location_callback函数的定义: [cpp] view plaincopy 731. static void location_callback(GpsLocation* location) 732. { 733. JNIEnv* env = AndroidRuntime::getJNIEnv(); 734. env->CallVoidMethod(mCallbacksObj, method_reportLocation, location->flags, 735. (jdouble)location->latitude, (jdouble)location->longitude, 736. (jdouble)location->altitude, 737. (jfloat)location->speed, (jfloat)location->bearing, 738. (jfloat)location->accuracy, (jlong)location->timestamp); 739. checkAndClearExceptionFromCallback(env, __FUNCTION__); 740. } 这里面利用JNI调用了Java语言的方法method_reportLocation,method_reportLocation是一个jmethodID变量,表示一个由Java语言定义的方法。下面我们看method_reportLocation的赋值代码: [cpp] view plaincopy 741. static void android_location_GpsLocationProvider_class_init_native(JNIEnv* env, jclass clazz) { 742. method_reportLocation = env->GetMethodID(clazz, "reportLocation", "(IDDDFFFJ)V"); 743. //...省略部分代码 744. } 这里表示method_reportLocation指向Java类clazz里的方法reportLocation,那么这个Java类clazz是不是表示GpsLocationProvider呢?我们找到注册JNI方法的方法表: [cpp] view plaincopy 745. tatic JNINativeMethod sMethods[] = { 746. /* name, signature, funcPtr */ 747. {"class_init_native", "()V", (void *)android_location_GpsLocationProvider_class_init_native}, 748. //...省略部分代码 749. } 这里说明_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 plaincopy 750. static { class_init_native(); } 说明是在GpsLocationProvider中调用了class_init_native方法,从而说明GpsLocationProvider的reportLocation函数是GpsCallbacks的回调函数,即当Gps设备的位置信息发生变化时,它调用GpsLocationProvider的回调函数reportLocation,继而调用LocationManagerService的reportLocation函数,从而更新应用层的位置信息。

你可能感兴趣的:(GPS源码)