Android系统Gps分析(一)
1 GPS架构

2 GPS分析
2.1 头文件
头文件定义在:hardware/libhardware/include/hardware/gps.h,定义了GPS底层相关的结构体和接口
-
GpsLocation
GPS位置信息结构体,包含经纬度,高度,速度,方位角等。
- /** Flags to indicate which values are valid in a GpsLocation. */
- typedef uint16_t GpsLocationFlags;
- // IMPORTANT: Note that the following values must match
- // constants in GpsLocationProvider.java.
- /** GpsLocation has valid latitude and longitude. */
- #define GPS_LOCATION_HAS_LAT_LONG 0x0001
- /** GpsLocation has valid altitude. */
- #define GPS_LOCATION_HAS_ALTITUDE 0x0002
- /** GpsLocation has valid speed. */
- #define GPS_LOCATION_HAS_SPEED 0x0004
- /** GpsLocation has valid bearing. */
- #define GPS_LOCATION_HAS_BEARING 0x0008
- /** GpsLocation has valid accuracy. */
- #define GPS_LOCATION_HAS_ACCURACY 0x0010
- /** Represents a location. */
- typedef struct {
- /** set to sizeof(GpsLocation) */
- size_t size;
- /** Contains GpsLocationFlags bits. */
- uint16_t flags;
- /** Represents latitude in degrees. */
- double latitude;
- /** Represents longitude in degrees. */
- double longitude;
- /** Represents altitude in meters above the WGS 84 reference
- * ellipsoid. */
- double altitude;
- /** Represents speed in meters per second. */
- float speed;
- /** Represents heading in degrees. */
- float bearing;
- /** Represents expected accuracy in meters. */
- float accuracy;
- /** Timestamp for the location fix. */
- GpsUtcTime timestamp;
- } GpsLocation;
-
GpsStatus
GPS状态包括5种状态,分别为未知,正在定位,停止定位,启动未定义,未启动。
- /** GPS status event values. */
- typedef uint16_t GpsStatusValue;
- // IMPORTANT: Note that the following values must match
- // constants in GpsLocationProvider.java.
- /** GPS status unknown. */
- #define GPS_STATUS_NONE 0
- /** GPS has begun navigating. */
- #define GPS_STATUS_SESSION_BEGIN 1
- /** GPS has stopped navigating. */
- #define GPS_STATUS_SESSION_END 2
- /** GPS has powered on but is not navigating. */
- #define GPS_STATUS_ENGINE_ON 3
- /** GPS is powered off. */AgpsCallbacks
- AgpsInterface
- #define GPS_STATUS_ENGINE_OFF 4
- /** Represents the status. */
- typedef struct {
- /** set to sizeof(GpsStatus) */
- size_t size;
- GpsStatusValue status;
- } GpsStatus;
-
GpsSvInfo
GPS卫星信息,包含卫星编号,信号强度,卫星仰望角,方位角等。
- /** Represents SV information. */
- typedef struct {
- /** set to sizeof(GpsSvInfo) */
- size_t size;
- /** Pseudo-random number for the SV. */
- int prn;
- /** Signal to noise ratio. */
- float snr;
- /** Elevation of SV in degrees. */
- float elevation;
- /** Azimuth of SV in degrees. */
- float azimuth;
- } GpsSvInfo;
-
GpsSvStatus
GPS卫星状态,包含可见卫星数和信息,星历时间,年历时间等。
- /** Represents SV status. */
- typedef struct {
- /** set to sizeof(GpsSvStatus) */
- size_t size;
- /** Number of SVs currently visible. */
- int num_svs;
- /** Contains an array of SV information. */
- GpsSvInfo sv_list[GPS_MAX_SVS];
- /** Represents a bit mask indicating which SVs
- * have ephemeris data.
- */
- uint32_t ephemeris_mask;
- /** Represents a bit mask indicating which SVs
- * have almanac data.
- */
- uint32_t almanac_mask;
- /**
- * Represents a bit mask indicating which SVs
- * were used for computing the most recent position fix.
- */
- uint32_t used_in_fix_mask;
- } GpsSvStatus;
-
GpsCallbacks
回调函数定义
- /** Callback with location information. 向上层传递GPS位置信息
- * Can only be called from a thread created by create_thread_cb.
- */
- typedef void (* gps_location_callback)(GpsLocation* location);
- /** Callback with status information. 向上层传递GPS状态信息
- * Can only be called from a thread created by create_thread_cb.
- */
- typedef void (* gps_status_callback)(GpsStatus* status);
- /** Callback with SV status information. 向上层传递GPS卫星信息
- * Can only be called from a thread created by create_thread_cb.
- */
- typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
- /** Callback for reporting NMEA sentences. 向上层传递MEMA数据
- * Can only be called from a thread created by create_thread_cb.
- */
- typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);
- /** Callback to inform framework of the GPS engine's capabilities.告知GPS模块可以实现的功能
- * Capability parameter is a bit field of GPS_CAPABILITY_* flags.
- */
- typedef void (* gps_set_capabilities)(uint32_t capabilities);
- /** Callback utility for acquiring the GPS wakelock.上锁,防止处理GPS事件时中止。
- * This can be used to prevent the CPU from suspending while handling GPS events.
- */
- typedef void (* gps_acquire_wakelock)();
- /** Callback utility for releasing the GPS wakelock. */释放锁
- typedef void (* gps_release_wakelock)();
- /** Callback for creating a thread that can call into the Java framework code.等待上层请求
- * This must be used to create any threads that report events up to the framework.
- */
- typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);
- /** GPS callback structure. */
- typedef struct {
- /** set to sizeof(GpsCallbacks) */
- 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接口是最重要的结构体,上层是通过此接口与硬件适配层交互的。
- /** Represents the standard GPS interface. */
- typedef struct {
- /** set to sizeof(GpsInterface) */
- size_t size;
- /**
- * Opens the interface and provides the callback routines
- * to the implemenation of this interface.
- */
- int (*init)( GpsCallbacks* callbacks );
- /** Starts navigating. 启动定位*/
- int (*start)( void );
- /** Stops navigating. 取消定位*/
- int (*stop)( void );
- /** Closes the interface. 关闭GPS接口*/
- void (*cleanup)( void );
- /** Injects the current time.填入时间 */
- int (*inject_time)(GpsUtcTime time, int64_t timeReference,
- int uncertainty);
- /** Injects current location from another location provider填入位置
- * (typically cell ID).
- * latitude and longitude are measured in degrees
- * expected accuracy is measured in meters
- */
- int (*inject_location)(double latitude, double longitude, float accuracy);
- /**
- * Specifies that the next call to start will not use the删除全部或部分辅助数据,在性能测试时使用
- * information defined in the flags. GPS_DELETE_ALL is passed for
- * a cold start.
- */
- void (*delete_aiding_data)(GpsAidingData flags);
- /**设置定位模式和GPS工作模式等
- * min_interval represents the time between fixes in milliseconds.
- * preferred_accuracy represents the requested fix accuracy in meters.
- * preferred_time represents the requested time to first fix in milliseconds.
- */
- int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
- uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);
- /** Get a pointer to extension information. 自定义的接口*/
- const void* (*get_extension)(const char* name);
- } GpsInterface;
-
gps_device_t
GPS设备结构体,继承自hw_device_tcommon,硬件适配接口,向上层提供了重要的get_gps_interface接口。
- struct gps_device_t {
- struct hw_device_t common;
- /**
- * Set the provided lights to the provided values.
- *
- * Returns: 0 on succes, error code on failure.
- */
- const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
- };
2.2硬件适配层
GPS硬件适配层的源码位于:hardware/qcom/gps目录下。
我们看gps/loc_api/llibloc_api/gps.c,首先定义了gps设备模块实例:
- 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
- static struct hw_module_methods_t gps_module_methods = {
- .open = open_gps
- };
gps_module_methods定义了设备的open函数为open_gps,我们看open_gps函数:
- 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的定义如下:
- const GpsInterface* gps__get_gps_interface(struct gps_device_t* dev)
- {
- return get_gps_interface();
- }
用代码跟踪可看到,此函数返回了gps/loc_eng.cpp文件的sLocEngInterface变量,sLocEngInterface定义如下:
- // 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方法的函数定义:
- int register_android_server_location_GpsLocationProvider(JNIEnv* env)
- {
- return jniRegisterNativeMethods(env, "com/android/server/location/GpsLocationProvider", sMethods, NELEM(sMethods));
- }
此函数被同目录下onload.cpp文件调用,调用地方在:
- 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定义如下:
- static JNINativeMethod sMethods[] = {
- /* name, signature, funcPtr */
- {"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:
- 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方法定义如下:
- 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()函数的实现:
- 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重要的接口和类作一个简单的介绍
-
接口
用于当Gps状态发生变化时接收通知 |
|
用于接收Gps的NMEA数据 |
|
用于接收当位置信息发生变化时,LocationManager发出的通知 |
-
类
地址信息类 |
|
用于根据设备情况动态选择provider |
|
用于处理地理编码信息 |
|
用于获取当前卫星状态 |
|
用于获取当前Gps状态 |
|
地理位置信息类 |
|
用于获取和操作gps系统服务 |
|
抽象类,用于提供位置提供者(Locationprovider) |
2.3.2 使用Gps编程接口
下面,我们用一个代码示例说明如何在应用层写一个简单的gps程序。
-
首先在AndroidManifest.xml中添加位置服务权限:
- <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>
-
接着获取位置信息:
- //获取位置服务
- 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();
- }
-
设置侦听,当位置信息发生变化时,自动更新相关信息
- //匿名类,继承自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
我们看其构造函数:
- public LocationManager(ILocationManager service) {
- mService = service;
- }
其中mService为ILocationManager接口类型,构造函数的参数为service,外部调用时传入LocationManagerService实例。LocationManager是android系统的gps位置信息系统服务,在稍后将会对其进行分析。由带参构造函数实例化LocationManager类的方式用得不多,一般用的方式是由getSystemService获得LocationManagerService服务,再强制转换为LocationManager。例如在2.3.2中的代码示例中是这样获取gps服务的:
- LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
这里的Context.LOCATION_SERVICE为”location”,标识gps服务。
LocationManagerService服务是整个GpsFramework的核心,首先看它是如何加载的,代码文件位于:frameworks/base/services/java/com/android/server/systemserver.java
- …//省略其他代码
- 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,其代码如下:
- /**
- * System private API for talking with the location service.
- *
- * {@hide}
- */
- 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(IGpsStatusL
最后更新:2017-04-03 12:55:57
上一篇:
freopen重定向stdin与stdout后如何恢复正常
下一篇:
Sql Server 常用命令小结