介绍完了主体代码结构以及重要的数据结构后,下面来看看gps的定位服务(LocationManager)的启动过程。
LocationManager 这项服务是在SystemServer.java 中启动的,也就是系统启动之后,这个服务就已经启动了:
systemServer.java [framework/base/services/java/com/android/server]
在 SystemServer.java 的 init2 函数中启动了一个线程来注册 Android 的诸多服务,如: Bluetooth
Service , NetworkManagement Service , Notification Manager 等,当然也包括 Location
Service 。
SystemServer.java [frameworks/base/services/java/com/android/server]
public static final void init2( ) {
Slog. i( TAG, "Entered the Android system server!" ) ;
Thread thr = new ServerThread( ) ;
thr. setName ( "android.server.ServerThread" ) ;
thr. start ( ) ;
}
在 ServerThread 线程的 run 函数中 LocationManager 服务的代码段如下:
2. 1版本
try {
Log . i( TAG, "Location Manager" ) ;
ServiceManager. addService ( Context . LOCATION_SERVICE, new LocationManagerService( context ) ) ;
} catch ( Throwable e) {
Log . e( TAG, "Failure starting Location Manager" , e) ;
}
2. 2的代码中代码段如下形式:
try {
Slog. i( TAG, "Location Manager" ) ;
location = new LocationManagerService( context ) ;
ServiceManager. addService ( Context . LOCATION_SERVICE, location ) ;
} catch ( Throwable e) {
Slog. e( TAG, "Failure starting Location Manager
在 run 函数的后半部分,是服务对系统的反馈,就是 systemReady() 函数。 LocationManager 服务的反馈函数如下:
if ( locationF ! = null ) locationF. systemReady( ) ;
其中的 locationF 是 LocationManagerService 的 final 类型,就是一旦赋值,不能更改。
final LocationManagerService locationF = location ;
哇! locationManager 这项服务的反馈机制只在 2.2 的代码里面才有啊。 2.1 中的反馈机制中并没有 locationManager (当然有其他的服务反馈)。
而在 2.1 版本中 LocationManagerService 的构造函数如下:
LocationManagerService.java [frameworks/base/services/java/com/android/server]
public LocationManagerService( Context context ) {
super ( ) ;
mContext = context ;
Thread thread = new Thread ( null , this , "LocationManagerService" ) ;
thread . start ( ) ;
if ( LOCAL_LOGV) {
Log . v( TAG, "Constructed LocationManager Service" ) ;
}
}
2.2版本
public LocationManagerService( Context context ) {
super ( ) ;
mContext = context ;
if ( LOCAL_LOGV) {
Slog. v( TAG, "Constructed LocationManager Service" ) ;
}
}
2.1 是在构造函数的时候就启动一个自身服务线程。见构造函数。
2.2 是在反馈机制中通过 systemReady 函数启动自身服务线程。如下:
void systemReady( ) {
// we defer starting up the service until the system is ready
Thread thread = new Thread ( null , this , "LocationManagerService" ) ;
thread . start ( ) ;
}
通过线程 run 函数,调用 initialize 函数 :
public void run ( )
{
Process . setThreadPriority( Process . THREAD_PRIORITY_BACKGROUND) ;
Looper. prepare ( ) ;
mLocationHandler = new LocationWorkerHandler( ) ;
initialize ( ) ;
Looper. loop ( ) ;
}