
5.4 在穿戴设备中实现GPS定位
在本节的内容中将通过具体实例来演示在Android穿戴设备中使用地图系统的基本流程。

本实例的具体实现流程如下所示。
(1)在文件AndroidManifest.xml中添加ACCESS_FINE_LOCATION权限,具体代码如下所示。

(2)在onCreate(Bundle savedInstanceState)中获取当前位置信息,具体代码如下所示。


在上述代码中,LocationManager用于周期获得当前设备的一个类。要想获取LocationManager实例,必须调用Context.getSystemService()方法并传入服务名LOCATION_SERVICE("location")。创建LocationManager实例后,即可通过调用getLast-KnownLocation()方法将上一次LocationManager获得有效位置信息以Location对象的形式返回。getLastKnownLocation()方法需要传入一个字符串参数来确定使用定位服务类型,本实例传入的是静态常量LocationManager.GPS_PROVIDER,这表示使用GPS技术定位。最后还需要使用Location对象将位置信息以文本方式显示到用户界面。
(3)定义方法updateWithNewLocation(Location location)来更新显示用户界面,具体代码如下所示。

(4)定义LocationListener对象locationListener,当坐标改变时触发此函数。如果Provider传进相同的坐标,它就不会被触发。具体代码如下所示。

下面开始测试,因为模拟器上没有GPS设备,所以需要在Eclipse的DDMS工具中提供模拟的GPS数据。即依次单击【DDMS】|【Emulator Control】,在弹出对话框中找到“Location Control”选项,在此输入坐标,完成后单击“Send”按钮,如图5-6所示。

图5-6 设置坐标
因为用到了Google API,所以要在项目中引入Google API,右击项目选择“Properties”,在弹出对话框中选择Google API版本,如图5-7所示。

图5-7 引用Google API
模拟器运行后会显示当前的坐标,如图5-8所示。

图5-8 执行效果