Android中實現GPS定位的簡單例子
今天弄了一個多小時,寫了一個GPS獲取地理位置代碼的小例子,包括參考了網上的一些代碼,并且對代碼進行了一些修改,希望對大家的幫助。具體代碼如下: 要實用Adnroid平臺的GPS設備,首先需要添加上權限,所以需要添加如下權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
具體實現代碼如下:
首先判斷GPS模塊是否存在或者是開啟:
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設置頁面:
獲取代碼如下:
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);
// 設置監(jiān)聽器,自動更新的最小時間為間隔N秒(1秒為1*1000,這樣寫主要為了方便)或最小位移變化超過N米
locationManager.requestLocationUpdates(provider, 100 * 1000, 500,
locationListener); }
到這里就可以獲取到地理位置信息了,但是還是要顯示出來,那么就用下面的方法進行顯示:
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("無法獲取地理信息");
}
}
這樣子就能獲取到當前使用者所在的地理位置了,至少如何下地圖上實現,在下面將進行獲取,并顯示出來!對參考代碼的人表示感謝!
相關文章
基于Android實現點擊某個按鈕讓菜單選項從按鈕周圍指定位置彈出
這篇文章主要介紹了基于Android實現點擊某個按鈕讓菜單選項從按鈕周圍指定位置彈出的相關資料,需要的朋友可以參考下2015-12-12
Android CardView+ViewPager實現ViewPager翻頁動畫的方法
本篇文章主要介紹了Android CardView+ViewPager實現ViewPager翻頁動畫的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
Android中Service和Activity相互通信示例代碼
在android中Activity負責前臺界面展示,service負責后臺的需要長期運行的任務。下面這篇文章主要給大家介紹了關于Android中Service和Activity相互通信的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09

