在你的应用程序可以获取位置更新之前,需要执行一些简单的步骤去设置访问。这个课程,你将会学习这些必须的步骤。
在Android清单文件中声明合适权限
设置位置更新访问的第一步是在清单文件中声明合适权限。如果没有声明,应用程序将会在运行时获取一个SecurityException异常。
ACCESS_COARSE_LOCATION或者ACCESS_FINE_LOCATION权限是使用LoactionManger方法所必须依靠的。例如,如果你的应用程序仅仅使用基于网络的位置提供者,你需要声明ACCESS_COARSE_LOCATION权限。更高精度的GPS需要ACCESS_FINE_LOCATION权限。注意声明ACCESS_FINE_LOCATION权限已经包含了ACCESS_COARSE_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);
选择一个位置提供者
虽然没有必要,许多现在的Android设备可以通过多个底层的技术获取位置更新,它们从应用程序中被抽象为一个LocationProvider对象。通常来说不同的位置提供者在定位时间,精度,费用和电量消耗等方面拥有不同的运行特性。相比于低精度的基于网络的位置提供者,一个拥有高精度的位置提供者,如GPS,需要更长的定位时间。
基于你的应用程序的使用案例,你必须选择一个明确的位置提供者,或者基于类似的平衡选择多个位置提供者。例如,一个标注感兴趣地点的应用程序比一个零售商定位器需要更高的精度的定位,后者只需要城市级别的定位就可以满足了。下面的代码片段请求返回一个GPS提供者。
LocationProvider provider =locationManager.getProvider(LocationManager.GPS_PROVIDER);
作为一种选择,你可以提供一些如精度,电源要求,费用消耗等输入条件,让Android选择一个最接近要求的位置提供者。下面的代码片段需要一个良好精度且免费的位置提供者。注意这个条件无法选择出任何一个提供者,在这种情况下一个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) {
...
}
核实内容提供者是否可用
如同GPS一样,一些位置提供者可以在设置中设置为不可用状态。通过调用isProviderEnabled()方法去检查希望得到的位置提供者当前是否可用是个良好的方法。如果提供者是不可用的,你通过激活一个ACTION_LOCATION_SOURCE_SETTINGS动作的意图,向用户提供一个启用它的机会。
@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);
}
文档目录:Developers/Training/Advanced Training/Making Your App Location Aware/Using the Location Manager
新技术,新未来!欢迎大家关注“1024工场”微信服务号,时刻关注我们的最新的技术讯息!(甭客气!尽情的扫描或者长按!)