Android GPS應用:動態獲取位置信息


在上文中,介紹了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 {
	// 定義LocationManager對象
	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 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// 從GPS獲取最近的定位信息
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		// 將location里的位置信息顯示在EditText中
		updateView(location);
		// 設置每2秒獲取一次GPS的定位信息
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				2000, 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(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 {
			// 如果傳入的Location對象為空則清空EditText
			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導航系統。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM