使用本地管理器
在你的应用程序可以定位之前,需要设置一些权限。这节课,你将学会这些步骤。
在Manifest文件中声明权限
定位的第一步就是在manifest中设置权限。如果权限缺失,应用程序将会报
SecurityException
错误。
由于
LocationManager
方法的使用,因此需要ACCESS_COARSE_LOCATION
or ACCESS_FINE_LOCATION
权限。例如,你必须声明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
是你的应用实现定位的主要类。同其他系统服务一样,可以通过getSystemService()
获取一个引用。如果你的应用程序意图获得定位信息在前台(任意一个Activity中),你应该实现这一步在 onCreate()
方法中。
LocationManager locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
选择一个定位提供者
有多种定位的技术可供选择,抽象为
LocationProvider
对象.不同提供者表现为不同的特性,比如时间,精确性,花费,电量等等。通常更高精度的服务,比如GPS,比精确度低一点的网络定位更加费时。
根据不同需求来选择服务。比如,一个签到程序也许需要更高的精确度,一家零售店的位置使用一般水平的定位就能够满足。
获取GPS
LocationProvider provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER);
// 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设置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);
}
未完待续。。。