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); // 設置監聽器,自動更新的最小時間為間隔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("無法獲取地理信息"); } }這樣子就能獲取到當前使用者所在的地理位置了,至少如何下地圖上實現,在下面將進行獲取,并顯示出來!對參考代碼的人表示感謝!
轉自:http://www.cnblogs.com/fly_binbin/archive/2010/12/16/1908518.html
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!