Using the Location Manager
在manifest中進行權限設置
要使用Android位置服務,需要設置ACCESS_COARSE_LOCATION或者ACCESS_FINE_LOCATION權限。
如果權限沒有設置,將會在運行時拋出一個 SecurityException異常。
如果只需要基於網絡的定位,可以只聲明ACCESS_COARSE_LOCATION權限;更加精確的GPS定位需要聲明 ACCESS_FINE_LOCATION 權限。需要注意的是后者已經包含了前者。
另外,如果應用中使用了基於網絡的定位,還要聲明網絡權限。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" />
得到LocationManager的一個引用
LocationManager 是Android位置服務應用中一個主要的類。
和其他系統服務類似,可以通過調用 getSystemService() 方法獲得一個引用。
如果你的應用希望在前景進程中接收位置更新,通常需要在Activity的onCreate()方法中調用這個方法:
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
選擇Location Provider
現在的Android都可以通過多種底層技術獲得位置的更新,這些底層技術被抽象成LocationProvider 類的對象。
各種Location Provider擁有不同的性能,比如定位時間、精確度、能耗等。
一般來說,高精確度的Location Provider,比如GPS,需要更長的定位時間,相比於低精確度的基於網絡的方法來說。
獲得GPS provider:
LocationProvider provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER);
可以設置一些標准,讓Android系統選擇一個最接近的匹配,從而選出location provider。
注意到這些標准可能得不到任何provider,這時候返回一個null。
// 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) { ... }
確認Location Provider是否使能
一些location provider可以在設置(Settings)中關閉,比如GPS。實踐中最好先驗證一下目標location provider是否使能,可以通過調用isProviderEnabled() 方法實現。
如果location provider是disabled狀態,你可以提供給用戶一個機會去在設置中打開它,通過啟動一個action為ACTION_LOCATION_SOURCE_SETTINGS 的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); }
參考資料:
LocationManager
http://developer.android.com/reference/android/location/LocationManager.html
LocationProvider
http://developer.android.com/reference/android/location/LocationProvider.html
Using the Location Manager:
http://developer.android.com/training/basics/location/locationmanager.html
