在上文中,介绍了GPS概念及Android开发GPS应用涉及到的常用类和方法。在本文中,开发一个小应用,实时获取定位信息,包括用户所在的纬度、经度、高度、方向、移动速度等。代码如下:
Activity:
- package comhome.location;
-
- 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;
-
- public class LocationTestActivity extends Activity {
-
- private LocationManager locationManager;
- private EditText show;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- show = (EditText) findViewById(R.id.main_et_show);
-
- locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
-
- Location location = locationManager
- .getLastKnownLocation(LocationManager.GPS_PROVIDER);
-
- updateView(location);
-
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
- 2000, 8, new LocationListener() {
-
- @Override
- public void onLocationChanged(Location location) {
-
- updateView(location);
- }
-
- @Override
- public void onProviderDisabled(String provider) {
- updateView(null);
- }
-
- @Override
- public void onProviderEnabled(String provider) {
-
- updateView(locationManager
- .getLastKnownLocation(provider));
-
- }
-
- @Override
- public void onStatusChanged(String provider, int status,
- Bundle extras) {
- }
- });
- }
-
- private void updateView(Location location) {
- if (location != null) {
- StringBuffer sb = new StringBuffer();
- sb.append("实时的位置信息:\n经度:");
- sb.append(location.getLongitude());
- sb.append("\n纬度:");
- sb.append(location.getLatitude());
- sb.append("\n高度:");
- sb.append(location.getAltitude());
- sb.append("\n速度:");
- sb.append(location.getSpeed());
- sb.append("\n方向:");
- sb.append(location.getBearing());
- sb.append("\n精度:");
- sb.append(location.getAccuracy());
- show.setText(sb.toString());
- } else {
-
- show.setText("");
- }
- }
-
- }
布局XML:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <EditText
- android:id="@+id/main_et_show"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:cursorVisible="false"
- android:editable="false" />
-
- </LinearLayout>
权限:
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
附上图片效果:

如果把该程序与Google
Map结合,让程序根据GPS提供的信息实时地显示用户在地图上的位置,即可开发出GPS导航系统。
Android GPS应用:动态获取位置信息,布布扣,bubuko.com
Android GPS应用:动态获取位置信息
原文:http://www.cnblogs.com/zhuzhengwen1983/p/3618087.html