main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/show" android:layout_width="fill_parent" android:layout_height="wrap_content" android:editable="false" android:cursorVisible="false" /> </LinearLayout>
LocationTest.java
package org.crazyit.gps; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.EditText; /** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class LocationTest extends Activity { // 定义LocationManager对象 LocationManager locManager; // 定义程序界面中的EditText组件 EditText show; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 获取程序界面上的EditText组件 show = (EditText) findViewById(R.id.show); // 创建LocationManager对象 locManager = (LocationManager) getSystemService (Context.LOCATION_SERVICE); // 从GPS获取最近的最近的定位信息 Location location = locManager.getLastKnownLocation( LocationManager.GPS_PROVIDER); // 使用location根据EditText的显示 updateView(location); // 设置每3秒获取一次GPS的定位信息 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 3000, 8, new LocationListener() //① { @Override public void onLocationChanged(Location location) { // 当GPS定位信息发生改变时,更新位置 updateView(location); } @Override public void onProviderDisabled(String provider) { updateView(null); } @Override public void onProviderEnabled(String provider) { // 当GPS LocationProvider可用时,更新位置 updateView(locManager .getLastKnownLocation(provider)); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }); } // 更新EditText中显示的内容 public void updateView(Location newLocation) { if (newLocation != null) { StringBuilder sb = new StringBuilder(); sb.append("实时的位置信息: "); sb.append("经度:"); sb.append(newLocation.getLongitude()); sb.append(" 纬度:"); sb.append(newLocation.getLatitude()); sb.append(" 高度:"); sb.append(newLocation.getAltitude()); sb.append(" 速度:"); sb.append(newLocation.getSpeed()); sb.append(" 方向:"); sb.append(newLocation.getBearing()); show.setText(sb.toString()); } else { // 如果传入的Location对象为空则清空EditText show.setText(""); } } }
上面的程序中粗体字代码用于从Location中获取定位信息,包括用户的经度、纬度、高度、方向和移动速度等信息。程序中①号粗体宁代码通过LocationManager设置了一个监听器,该}监听器负责每隔3秒向LocationProvider请求一次定位信息,当LocationProvider可用时、不可用时或提供的定位信息发生改变时,系统会回调updateView(Location newLocation)来更新EditText中漫示的定位信息。
该程序需要有访问GPS信号的权限,因此需要在AndroidManifest.xml文件中增加如下授权代码片段:
<!-- 授权获取定位信息 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
截图: