Android使用位置管理器
只需要進行一些簡單的設置,你的應用程序就可以接受位置更新,在這次教程里你將詳細的學習這些步驟,讓你掌握Android位置管理器的使用方法。
一、在Manifest里聲明合適的權限
要想獲取位置更新,***步需要在manifest里聲明合適的權限。如果忘了聲明相應的權限,那么你的應用在運行時會報安全異常。當你使用LocationManagement方法的時候,需要設置權限ACCESS_CORASE_LOCATION或者 ACCESS_FINE_LOCATION,例如,如果你的應用使用了基于網絡的信息服務,你需要聲明N ACCESS_CORASE_LOATION權限,要想獲取GPS請求你需要聲明ACCESS_FINE_LOCATION權限。值得注意的是如果你聲明了ACCESS_FINE_LOCATION權限隱含著你也聲明了ACCESS_CORASE_LOCATION權限。 假如一個應用使用了基于網絡的位置的信息服務,你需要聲明因特網權限。
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.INTERNET" />
二、獲得一個位置管理的引用
LocationManager是一個主類,在android里你通過這個類你可以使位置服務。使用方法類似于其他的服務,通過調用 getSystemService方法可以獲得相應的引用。如果你的應用想要在前臺(在Activity里)獲得位置更新,你應該在onCreate() 里執行以下語句。
- LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
三、挑選一個位置提供者
當沒有請求的時候,現在大部分android電源管理可以通過多種底層技術可以獲得位置更新,這種技術被抽象為LocationProvider類的應 用。在時間、精度、成本、電源消耗等方面,位置提供者有不同的運行特性。通常,像GPS,一個精確的位置提供者,需要更長的修正時間,而不是不精確,比如 基于網絡的位置提供者。 通過權衡之后你必須選擇一種特殊的位置提供者,或者多重提供者,這些都依賴與你的應用的客戶需求。例如,比如說一個關鍵點的簽到服務,需要高精度定位,而 一個零售商店定位器使用城市級別的修正就可以滿足。下面的代碼段要求一個GPS提供者的支持。
- LocationProvider provider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
你提供一些輸入標準,比如精度、功率需求、成本等等,讓android決定一個最合適的位置匹配提供者。下邊的代碼片段需要的是更精確的位置提供者而不是 考慮成本。需要注意的是這個標準不能幫你解決任何的提供者,可能返回值為空。這個時候你的應用應該能夠很好的處理這種情況
- // Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setCostAllowed(false);
- ...
- String providerName = locManager.getBestProvider(criteria, true);
- // If no suitable provider is found, null is returned.
- if (providerName != null) {
- ...
- }
四、檢查位置提供者是否使能
在設置里,一些位置提供者比如GPS可以被關閉。良好的做法就是通過調用isProviderEnabled()方法來檢測你想要的位置提供者是否打開。如果位置提供者被關閉了,你可以在設置里通過啟動Intent來讓用戶打開。
- @Override
- protected void onStart() {
- super.onStart();
- // This verification should be done during onStart() because the system calls
- // this method when the user returns to the activity, which ensures the desired
- // location provider is enabled each time the activity resumes from the stopped state.
- LocationManager locationManager =
- (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- if (!gpsEnabled) {
- // Build an alert dialog here that requests that the user enable
- // the location services, then when the user clicks the "OK" button,
- // call enableLocationSettings()
- }
- }
- private void enableLocationSettings() {
- Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivity(settingsIntent);
- }
希望本文讓讀者朋友們對學習Android位置管理器一定的幫助和啟發。























