首先直接貼代碼:
package com.example.gpstest;
import java.util.Iterator;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
private LocationManager lm;
private static final String TAG = "GpsActivity";
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
lm.removeUpdates(locationListener);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 判斷GPS是否正常啓動
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "請開啓GPS導航...", Toast.LENGTH_SHORT).show();
// 返回開啓GPS導航設置界面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 0);
return;
}
// 爲獲取地理位置信息時設置查詢條件
String bestProvider = lm.getBestProvider(getCriteria(), true);
// 獲取位置信息
// 如果不設置查詢要求,getLastKnownLocation方法傳人的參數爲LocationManager.GPS_PROVIDER
Location location = lm.getLastKnownLocation(bestProvider);
updateView(location);
// 監聽狀態
lm.addGpsStatusListener(listener);
// 綁定監聽,有4個參數
// 參數1,設備:有GPS_PROVIDER和NETWORK_PROVIDER兩種
// 參數2,位置信息更新週期,單位毫秒
// 參數3,位置變化最小距離:當位置距離變化超過此值時,將更新位置信息
// 參數4,監聽
// 備註:參數2和3,如果參數3不爲0,則以參數3爲準;參數3爲0,則通過時間來定時更新;兩者爲0,則隨時刷新
// 1秒更新一次,或最小位移變化超過1米更新一次;
// 注意:此處更新準確度非常低,推薦在service裏面啓動一個Thread,在run中sleep(10000);然後執行handler.sendMessage(),更新位置
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
}
// 位置監聽
private LocationListener locationListener = new LocationListener() {
/**
* 位置信息變化時觸發
*/
public void onLocationChanged(Location location) {
updateView(location);
Log.i(TAG, "時間:" + location.getTime());
Log.i(TAG, "經度:" + location.getLongitude());
Log.i(TAG, "緯度:" + location.getLatitude());
Log.i(TAG, "海拔:" + location.getAltitude());
}
/**
* GPS狀態變化時觸發
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
// GPS狀態爲可見時
case LocationProvider.AVAILABLE:
Log.i(TAG, "當前GPS狀態爲可見狀態");
break;
// GPS狀態爲服務區外時
case LocationProvider.OUT_OF_SERVICE:
Log.i(TAG, "當前GPS狀態爲服務區外狀態");
break;
// GPS狀態爲暫停服務時
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.i(TAG, "當前GPS狀態爲暫停服務狀態");
break;
}
}
/**
* GPS開啓時觸發
*/
public void onProviderEnabled(String provider) {
Location location = lm.getLastKnownLocation(provider);
updateView(location);
}
/**
* GPS禁用時觸發
*/
public void onProviderDisabled(String provider) {
updateView(null);
}
};
// 狀態監聽
GpsStatus.Listener listener = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
switch (event) {
// 第一次定位
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.i(TAG, "第一次定位");
break;
// 衛星狀態改變
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.i(TAG, "衛星狀態改變");
// 獲取當前狀態
GpsStatus gpsStatus = lm.getGpsStatus(null);
// 獲取衛星顆數的默認最大值
int maxSatellites = gpsStatus.getMaxSatellites();
// 創建一個迭代器保存所有衛星
Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
.iterator();
int count = 0;
while (iters.hasNext() && count <= maxSatellites) {
GpsSatellite s = iters.next();
count++;
}
System.out.println("搜索到:" + count + "顆衛星");
editText.append("\n獲取的衛星數:"+count);
break;
// 定位啓動
case GpsStatus.GPS_EVENT_STARTED:
Log.i(TAG, "定位啓動");
break;
// 定位結束
case GpsStatus.GPS_EVENT_STOPPED:
Log.i(TAG, "定位結束");
break;
}
};
};
/**
* 實時更新文本內容
*
* @param location
*/
private void updateView(Location location) {
if (location != null) {
editText.setText("設備位置信息\n\n經度:");
editText.append(String.valueOf(location.getLongitude()));
editText.append("\n緯度:");
editText.append(String.valueOf(location.getLatitude()));
editText.append("\n海拔:");
editText.append(String.valueOf(location.getAltitude()));
editText.append("\n時間:");
editText.append(String.valueOf(location.getTime()));
editText.append("\n位置精度:");
editText.append(String.valueOf(location.getAccuracy()));
editText.append("\n速度:");
editText.append(String.valueOf(location.getSpeed()));
editText.append("\n方向角:");
editText.append(String.valueOf(location.getBearing()));
} else {
// 清空EditText對象
editText.getEditableText().clear();
}
}
/**
* 返回查詢條件
*
* @return
*/
private Criteria getCriteria() {
Criteria criteria = new Criteria();
// 設置定位精確度 Criteria.ACCURACY_COARSE比較粗略,Criteria.ACCURACY_FINE則比較精細
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 設置是否要求速度
criteria.setSpeedRequired(false);
// 設置是否允許運營商收費
criteria.setCostAllowed(false);
// 設置是否需要方位信息
criteria.setBearingRequired(false);
// 設置是否需要海拔信息
criteria.setAltitudeRequired(false);
// 設置對電源的需求
criteria.setPowerRequirement(Criteria.POWER_LOW);
return criteria;
}
}
佈局的話,就只要一個EditText控件:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="50dp"
android:ems="10"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
最重要的是在AndroidMainfest.xml文件中添加gps權限:
<manifest
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
注意:要添加到中間去。
運行之後的界面是這樣的:
如果不想出現那麼多的出現衛星的數量,你可以註銷掉這句代碼: editText.append(“\n獲取的衛星數:”+count);