今天弄了一個(gè)多小時(shí),寫了一個(gè)GPS獲取地理位置代碼的小例子,包括參考了網(wǎng)上的一些代碼,并且對代碼進(jìn)行了一些修改,希望對大家的幫助。具體代碼如下: 要實(shí)用Adnroid平臺(tái)的GPS設(shè)備,首先需要添加上權(quán)限,所以需要添加如下權(quán)限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
具體實(shí)現(xiàn)代碼如下:
首先判斷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); //此為設(shè)置完成后返回到獲取界面 }
如果開啟正常,則會(huì)直接進(jìn)入到顯示頁面,如果開啟不正常,則會(huì)進(jìn)行到GPS設(shè)置頁面:
獲取代碼如下:
private void getLocation() { // 獲取位置管理服務(wù) LocationManager locationManager; String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) this.getSystemService(serviceName); // 查找到服務(wù)信息 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); // 設(shè)置監(jiān)聽器,自動(dòng)更新的最小時(shí)間為間隔N秒(1秒為1*1000,這樣寫主要為了方便)或最小位移變化超過N米 locationManager.requestLocationUpdates(provider, 100 * 1000, 500, locationListener); }
到這里就可以獲取到地理位置信息了,但是還是要顯示出來,那么就用下面的方法進(jìn)行顯示:
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經(jīng)度" + longitude); } else { tv1.setText("無法獲取地理信息"); } }
這樣子就能獲取到當(dāng)前使用者所在的地理位置了,至少如何下地圖上實(shí)現(xiàn),在下面將進(jìn)行獲取,并顯示出來!對參考代碼的人表示感謝!
|
新聞熱點(diǎn)
疑難解答
圖片精選