今天弄了一個多小時,寫了一個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("無法擷取地理資訊"); } }
這樣子就能擷取到當前使用者所在的地理位置了,至少如何下地圖上實現,在下面將進行擷取,並顯示出來!對參考代碼的人表示感謝!