LocationManagerService(简称LMS)和Android Java Framework中的其他Service一样由SystemServer创建并运行在system_process进程中。LMS是系统Location模块的核心,我们来看一下它的初始化。
目录:frameworks/base/services/core/java/com/android/server
1. SystemServer.java
在SystemServer.java文件中,startOtherService函数创建LMS的代码如下,首先创建了LMS对象,并将LOCATION_SERVICE添加到ServiceManager中。
if (!disableLocation) {
try {
Slog.i(TAG, "Location Manager");
location = new LocationManagerService(context);
ServiceManager.addService(Context.LOCATION_SERVICE, location);
} catch (Throwable e) {
reportWtf("starting Location Manager", e);
}
同样是在startOtherService函数中,调用了LMS的systemRunning函数,代码如下:
try {
if (locationF != null) locationF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying Location Service running", e);
}
2. LMS(LocationManagerService)
LMS的systemRunning函数实现如下:
public void systemRunning() {
synchronized (mLock) {
if (D) Log.d(TAG, "systemReady()");
// fetch package manager
mPackageManager = mContext.getPackageManager();
// fetch power manager
mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
// prepare worker thread
mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
// prepare mLocationHandler's dependents
// Android平台提供粗细两种精度的位置信息。其中,粗精度的位置信息由LocationFudger根据细精度的位置
// 信息进行一定的数学模糊处理后得到。
mLocationFudger = new LocationFudger(mContext, mLocationHandler);
// 系统有一个黑白名单用于禁止使用某些特定的LP,在黑白名单中,LP由其对应的java包名指定
mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
mBlacklist.init();
//GeofenceManager为地理围栏对象。
mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
// prepare providers 关键函数
loadProvidersLocked();
// 根据设置中的开关情况,开启或者禁止某个LP。在此函数中,各LP实现的LocationProviderInterface接口的enable/disable函数被调用
updateProvidersLocked();
}
// listen for settings changes 监听设置数据库的变化,字段LOCATION_PROVIDERS_ALLOWED,当用户点击设置菜单按钮时,会改变数据库该字段的值
mContext.getContentResolver().registerContentObserver(
Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
new ContentObserver(mLocationHandler) {
@Override
public void onChange(boolean selfChange) {
synchronized (mLock) {
updateProvidersLocked();
}
}
}, UserHandle.USER_ALL);
mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
// 其他如监听用户切换,APK安装/卸载等事件在此不赘述
... ...
}
systemRunning中的内容较多,我们看其中的关键函数:loadProvidersLocked(),该函数用于创建及加载系统中所有的LP,其代码如下: