標籤:
GPS定位貌似在室內用不了,今天自己弄了一個GPS定位小Demo,包括使用者所在的經度、緯度、高度、方向、移動速度、精確度等資訊。Android為GPS功能支援專門提供了一個LocationManager類,程式並不能直接建立LocationManager執行個體,而是通過Context的getSystemService()方法來擷取。
例如:LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
下面的程式很簡單,布局裡面只用了一個EditText顯示所有資料:
執行個體Demo:
MainActivity.java
package sn.qdj.localgpsdemo;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;/** * GPS定位 * @author qingdujun * */public class MainActivity extends Activity { LocationManager lm; EditText show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (EditText)findViewById(R.id.show); //建立LocationManager對象 lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //從GPS擷取最近的定位資訊 Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); //更新顯示定位資訊 updateView(lc); //設定每3秒 擷取一次GPS定位資訊 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // 當GPS LocationProvider可用時,更新定位 updateView(lm.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub updateView(null); } @Override public void onLocationChanged(Location location) { // 當GPS定位資訊發生改變時,更新定位 updateView(location); } }); } public void updateView(Location newLocation){ if (newLocation != null) { StringBuilder sb = new StringBuilder(); sb.append("即時位置資訊:\n"); sb.append("經度:\n"); sb.append(newLocation.getLongitude()); sb.append("\n緯度:"); sb.append(newLocation.getLatitude()); sb.append("\n高度:"); sb.append(newLocation.getAltitude()); sb.append("\n速度:"); sb.append(newLocation.getSpeed()); sb.append("\n方向:"); sb.append(newLocation.getBearing()); sb.append("\n定位精度:"); sb.append(newLocation.getAccuracy()); show.setText(sb.toString()); } else { show.setText(null); } }}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="sn.qdj.localgpsdemo.MainActivity" > <!-- 顯示定位資訊 --> <EditText android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="" /></RelativeLayout>
GPS定位需要添加一個許可權
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Android GPS定位