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