[html]
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
具體實現代碼如下:
首先判斷GPS模塊是否存在或者是開啟:
[java]
private void openGPSSettings() {
LocationManager alm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (alm
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模塊正常", Toast.LENGTH_SHORT)
.show();
return;
}
Toast.makeText(this, "請開啟GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent,0); //此為設置完成後返回到獲取界面
}
如果開啟正常,則會直接進入到顯示頁面,如果開啟不正常,則會進行到GPS設置頁面:
獲取代碼如下:
[java]
private void getLocation()
{
// 獲取位置管理服務
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(serviceName);
// 查找到服務信息
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true); // 獲取GPS信息
Location location = locationManager.getLastKnownLocation(provider); // 通過GPS獲取位置
updateToNewLocation(location);
// 設置監聽器,自動更新的最小時間為間隔N秒(1秒為1*1000,這樣寫主要為了方便)或最小位移變化超過N米
locationManager.requestLocationUpdates(provider, 100 * 1000, 500,
locationListener);
}
到這裡就可以獲取到地理位置信息了,但是還是要顯示出來,那麼就用下面的方法進行顯示:
[java]
<strong><span style="font-size:14px;">private void updateToNewLocation(Location location) {
TextView tv1;
tv1 = (TextView) this.findViewById(R.id.tv1);
if (location != null) {
double latitude = location.getLatitude();
double longitude= location.getLongitude();
tv1.setText("維度:" + latitude+ "\n經度" + longitude);
} else {
tv1.setText("無法獲取地理信息");
}
}</span></strong>