1 車載啟動(dòng)流程
車載Android啟動(dòng)流程基本是在Android系統(tǒng)的啟動(dòng)流程中,多了Car相關(guān)服務(wù)。其他流程基本一致,下面我們來看一下Android系統(tǒng)的啟動(dòng)流程。
1.1 Android系統(tǒng)啟動(dòng)流程
Android系統(tǒng)的啟動(dòng),從設(shè)備的開機(jī)鍵長(zhǎng)按開始到Android桌面展示,這個(gè)完整流程就是Android系統(tǒng)啟動(dòng)的流程。從系統(tǒng)層次角度可分為L(zhǎng)inux 系統(tǒng)層、Android 系統(tǒng)服務(wù)層、Zygote進(jìn)程模型三個(gè)階段;從開機(jī)到啟動(dòng)Android桌面完成具體細(xì)節(jié)可分為Android系統(tǒng)啟動(dòng)的七個(gè)步驟。下面我們來分析一下:

1.1.1 啟動(dòng)電源啟動(dòng)系統(tǒng)
觸當(dāng)電源按下時(shí)引導(dǎo)芯片從預(yù)定義的地方(固化在ROM)開始執(zhí)行。加載引導(dǎo)程序BootLoader到RAM中,然后執(zhí)行。
1.1.2 啟動(dòng)BootLoader引導(dǎo)程序
引導(dǎo)程序BootLoader是在Android操作系統(tǒng)開始運(yùn)行前的一個(gè)小程序,它的主要作用是將AndroidOS拉起來。
1.1.3 啟動(dòng)linux內(nèi)核
當(dāng)內(nèi)核啟動(dòng)時(shí),設(shè)置緩存、被保護(hù)存儲(chǔ)器、計(jì)劃列表、加載驅(qū)動(dòng)。當(dāng)內(nèi)核完成系統(tǒng)設(shè)置后,它首先會(huì)在系統(tǒng)文件中尋找init.rc文件,并啟動(dòng)init.rc進(jìn)程。
1.1.4 啟動(dòng)init進(jìn)程
init進(jìn)程啟動(dòng)做了很多工作,但是總的來說主要就是做了一下三件事:
(1)創(chuàng)建和掛載啟動(dòng)所需文件目錄。
(2)初始化和啟動(dòng)系統(tǒng)屬性服務(wù)。
(3)解析init.rc配置文件并啟動(dòng)Zygote進(jìn)程。
1.1.5 啟動(dòng)zygote進(jìn)程孵化器
程序上app_process進(jìn)程啟動(dòng)zygote進(jìn)程。zygote主要?jiǎng)?chuàng)建Java虛擬機(jī)并為Java虛擬機(jī)注冊(cè)JNI方法;創(chuàng)建服務(wù)端Socket;預(yù)加載類和資源;啟動(dòng)SystemServer進(jìn)程;等待AMS請(qǐng)求創(chuàng)建新的應(yīng)用進(jìn)程。
1.1.6 啟動(dòng)systemServer進(jìn)程
創(chuàng)建并啟動(dòng)Binder線程池,這樣可以和其他進(jìn)程進(jìn)行通信。
創(chuàng)建SystemServiceManager,其用于對(duì)系統(tǒng)的服務(wù)進(jìn)行創(chuàng)建、啟動(dòng)和生命周期的管理。
啟動(dòng)系統(tǒng)中的各種服務(wù)。包括我們熟悉的AMS、PMS、WMS。
1.1.7 啟動(dòng)Launcher
被SystemServer啟動(dòng)的AMS會(huì)啟動(dòng)Launcher,Launcher啟動(dòng)后會(huì)將已安裝應(yīng)用的圖標(biāo)顯示在桌面上。

1.2 車載Android啟動(dòng)的區(qū)別
車載Android啟動(dòng)是在前面1.1Android系統(tǒng)啟動(dòng)流程中SystemServer開始,有區(qū)別。車載Android在SystemServer中啟動(dòng)獨(dú)有的CarService。下圖虛線部分

2 車載CarService啟動(dòng)
CarService是車載Android系統(tǒng)的核心服務(wù)之一,所有應(yīng)用都需要通過CarService來查詢、控制整車的狀態(tài)。不僅僅是車輛控制,實(shí)際上CarService幾乎就是整個(gè)車載Framework最核心的組件。提供了一系列的服務(wù)與HAL層的VehicleHAL通信,進(jìn)而通過車載總線(例如CAN總線)與車身進(jìn)行通訊,同時(shí)它們還為應(yīng)用層的APP提供接口,從而讓APP能夠?qū)崿F(xiàn)對(duì)車身的控制與狀態(tài)的顯示。
CarService啟動(dòng)流程和汽車相關(guān)的服務(wù)的啟動(dòng)主要依靠一個(gè)系統(tǒng)服務(wù)CarServiceHelperService開機(jī)時(shí)在SystemServer中啟動(dòng)。
2.1 CarServiceHelperService啟動(dòng)
SystemServer進(jìn)程啟動(dòng)后會(huì)調(diào)用main()->run()->startOtherService()方法,通過判斷當(dāng)前系統(tǒng)是否是車載分支的版本,是則創(chuàng)建CarServiceHelperService。
package com.android.server;
// ...
public final class SystemServer {
// ...
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
*/
private void startOtherServices() {
// ...
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
traceEnd();
}
// ...
}
// ...
}
SystemServer中使用Service管理代理SystemServiceManager的startService方法通過反射構(gòu)建com.android.internal.car.CarServiceHelperService。CarServiceHelperService也是繼承自SystemService,初始化成功后調(diào)用onStart()方法啟動(dòng)。
/**
* Manages creating, starting, and other lifecycle events of
* {@link com.android.server.SystemService system services}.
*
* {@hide}
*/
public class SystemServiceManager {
// ...
/**
* Starts a service by class name.
*
* @return The service instance.
*/
@SuppressWarnings("unchecked")
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
throw new RuntimeException("Failed to create service " + className
+ ": service class not found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it", ex);
}
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
// ...
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
// ...
}
2.2 車載CarService進(jìn)程啟動(dòng)
onStart()方法中使用AIDL啟動(dòng)CarService(新的進(jìn)程),并加載jni庫(kù)為CarService提供必要的API。CarServiceHelperService重寫后的onStart()需要重點(diǎn)看一下:
package com.android.internal.car;
// ...
/**
* System service side companion service for CarService.
* Starts car service and provide necessary API for CarService. Only for car product.
*/
public class CarServiceHelperService extends SystemService {
// ...
private static final String CAR_SERVICE_INTERFACE = "android.car.ICar";
@Override
public void onStart() {
Intent intent = new Intent();
intent.setPackage("com.android.car");
intent.setAction(CAR_SERVICE_INTERFACE);
if (!getContext().bindServiceAsUser(intent, mCarServiceConnection,Context.BIND_AUTO_CREATE,UserHandle.SYSTEM)) {
Slog.wtf(TAG, "cannot start car service");
}
System.loadLibrary("car-framework-service-jni");
}
// ...
}
2.3 CarServer啟動(dòng)圖
大致流程分為以下幾步:
1.SystemServer初始化時(shí)候調(diào)用startOtherService()。
2.startOtherService()方法通過SystemServerManager對(duì)象的startService()啟動(dòng)CarServiceHelperService,并調(diào)用其onStart()方法。
3.CarServiceHelperService通過bindServiceAsUser()方法啟動(dòng)CarService
4.CarService被創(chuàng)建后,onCreate方法調(diào)用進(jìn)行初始化當(dāng)前對(duì)象。

3 車載CarService內(nèi)部實(shí)現(xiàn)

CarService進(jìn)入啟動(dòng)時(shí)序后,onCreate()方法中進(jìn)行一系列的自身的初始化操作,步驟如下:
1)通過HIDL接口獲取到HAL層的IHwBinder對(duì)象-IVehicle,與AIDL的用法類似,必須持有IHwBinder對(duì)象我們才可以與Vehicle HAL層進(jìn)行通信。
2)創(chuàng)建ICarImpl對(duì)象,并調(diào)用init方法,它就是ICar.aidl接口的實(shí)現(xiàn)類,我們需要通過它才能拿到其他的Service的IBinder對(duì)象。
3)將ICar.aidl的實(shí)現(xiàn)類添加到ServiceManager中。
4)設(shè)定SystemProperty,將CarService設(shè)定為創(chuàng)建完成狀態(tài),只有包含CarService在內(nèi)的所有的核心Service都完成初始化,才能結(jié)束開機(jī)動(dòng)畫并發(fā)送開機(jī)廣播。
@Override
public void onCreate() {
Log.i(CarLog.TAG_SERVICE, "Service onCreate");
mCanBusErrorNotifier = new CanBusErrorNotifier(this /* context */ );
mVehicle = getVehicle();
EventLog.writeEvent(EventLogTags.CAR_SERVICE_CREATE, mVehicle == null ? 0 : 1);
if (mVehicle == null) {
throw new IllegalStateException("Vehicle HAL service is not available.");
}
try {
mVehicleInterfaceName = mVehicle.interfaceDescriptor();
} catch (RemoteException e) {
throw new IllegalStateException("Unable to get Vehicle HAL interface descriptor", e);
}
Log.i(CarLog.TAG_SERVICE, "Connected to " + mVehicleInterfaceName);
EventLog.writeEvent(EventLogTags.CAR_SERVICE_CONNECTED, mVehicleInterfaceName);
mICarImpl = new ICarImpl(this,
mVehicle,
SystemInterface.Builder.defaultSystemInterface(this).build(),
mCanBusErrorNotifier,
mVehicleInterfaceName);
mICarImpl.init();
// 處理 HIDL 連接
linkToDeath(mVehicle, mVehicleDeathRecipient);
ServiceManager.addService("car_service", mICarImpl);
SystemProperties.set("boot.car_service_created", "1");
super.onCreate();
}
3.1 IVehicle對(duì)象創(chuàng)建
通過HIDL接口獲取到HAL層的IHwBinder對(duì)象-IVehicle,與AIDL的用法類似,必須持有IHwBinder對(duì)象我們才可以與Vehicle HAL層進(jìn)行通信。
@Nullable
private static IVehicle getVehicle() {
final String instanceName = SystemProperties.get("ro.vehicle.hal", "default");
try {
return android.hardware.automotive.vehicle.V2_0.IVehicle.getService(instanceName);
} catch (RemoteException e) {
Log.e(CarLog.TAG_SERVICE, "Failed to get IVehicle/" + instanceName + " service", e);
} catch (NoSuchElementException e) {
Log.e(CarLog.TAG_SERVICE, "IVehicle/" + instanceName + " service not registered yet");
}
return null;
}
3.2 實(shí)現(xiàn)Service服務(wù),ICarImpl實(shí)現(xiàn)
接著我們?cè)賮砜碔CarImpl的實(shí)現(xiàn),如下所示:
3.2.1 創(chuàng)建各個(gè)核心服務(wù)對(duì)象。
3.2.2 把服務(wù)對(duì)象緩存到CarLocalServices中,主要為了方便Service之間的相互訪問。
ICarImpl(Context serviceContext, IVehicle vehicle, SystemInterface systemInterface,
CanBusErrorNotifier errorNotifier, String vehicleInterfaceName,
@Nullable CarUserService carUserService,
@Nullable CarWatchdogService carWatchdogService) {
...
// 創(chuàng)建 核心服務(wù)對(duì)象
mCarPowerManagementService = new CarPowerManagementService(mContext, mHal.getPowerHal(),
systemInterface, mCarUserService);
...
// 將重要的服務(wù)緩存到 CarLocalServices
CarLocalServices.addService(CarPowerManagementService.class, mCarPowerManagementService);
CarLocalServices.addService(CarPropertyService.class, mCarPropertyService);
CarLocalServices.addService(CarUserService.class, mCarUserService);
CarLocalServices.addService(CarTrustedDeviceService.class, mCarTrustedDeviceService);
CarLocalServices.addService(CarUserNoticeService.class, mCarUserNoticeService);
CarLocalServices.addService(SystemInterface.class, mSystemInterface);
CarLocalServices.addService(CarDrivingStateService.class, mCarDrivingStateService);
CarLocalServices.addService(PerUserCarServiceHelper.class, mPerUserCarServiceHelper);
CarLocalServices.addService(FixedActivityService.class, mFixedActivityService);
CarLocalServices.addService(VmsBrokerService.class, mVmsBrokerService);
CarLocalServices.addService(CarOccupantZoneService.class, mCarOccupantZoneService);
CarLocalServices.addService(AppFocusService.class, mAppFocusService);
// 將創(chuàng)建的服務(wù)對(duì)象依次添加到一個(gè)list中保存起來
List<CarServiceBase> allServices = new ArrayList<>();
allServices.add(mFeatureController);
allServices.add(mCarUserService);
...
allServices.add(mCarWatchdogService);
// Always put mCarExperimentalFeatureServiceController in last.
addServiceIfNonNull(allServices, mCarExperimentalFeatureServiceController);
mAllServices = allServices.toArray(new CarServiceBase[allServices.size()]);
}
3.2.3 將服務(wù)對(duì)象放置一個(gè)list中。這樣init方法中就可以以循環(huán)的形式直接調(diào)用服務(wù)對(duì)象的init,而不需要一個(gè)個(gè)調(diào)用。VechicleHAL的程序也會(huì)在這里完成初始化。
@MainThread
void init() {
mBootTiming = new TimingsTraceLog(VHAL_TIMING_TAG, Trace.TRACE_TAG_HAL);
traceBegin("VehicleHal.init");
// 初始化 Vechicle HAL
mHal.init();
traceEnd();
traceBegin("CarService.initAllServices");
// 初始化所有服務(wù)
for (CarServiceBase service : mAllServices) {
service.init();
}
traceEnd();
}
3.2.4 最后實(shí)現(xiàn)ICar.aidl中定義的各個(gè)接口就可以了
@Override
public IBinder getCarService(String serviceName) {
if (!mFeatureController.isFeatureEnabled(serviceName)) {
Log.w(CarLog.TAG_SERVICE, "getCarService for disabled service:" + serviceName);
return null;
}
switch (serviceName) {
case Car.AUDIO_SERVICE:
return mCarAudioService;
case Car.APP_FOCUS_SERVICE:
return mAppFocusService;
case Car.PACKAGE_SERVICE:
return mCarPackageManagerService;
...
default:
IBinder service = null;
if (mCarExperimentalFeatureServiceController != null) {
service = mCarExperimentalFeatureServiceController.getCarService(serviceName);
}
if (service == null) {
Log.w(CarLog.TAG_SERVICE, "getCarService for unknown service:"
+ serviceName);
}
return service;
}
}
3.3 CarService運(yùn)行圖

3.4 總結(jié)
CarService實(shí)現(xiàn)的功能幾乎就是覆蓋整個(gè)車載Framework的核心。
然而現(xiàn)實(shí)中為了保證各個(gè)核心服務(wù)的穩(wěn)定性,同時(shí)降低CarService協(xié)同開發(fā)的難度,一般會(huì)選擇將一些重要的服務(wù)拆分單獨(dú)作為一個(gè)獨(dú)立的Service運(yùn)行在獨(dú)立的進(jìn)程中,導(dǎo)致有的車機(jī)系統(tǒng)中CarService只實(shí)現(xiàn)了CarPropertyService的功能。
CarService實(shí)現(xiàn)流程可以這樣理解:提供IVehicle對(duì)象與底層交互,提供ICarImpl初始化一系列服務(wù)交給ServiceManager管理,而這些服務(wù)可以通過IVehicle對(duì)象調(diào)用底層的API,CarService充當(dāng)一個(gè)中介代理的角色存在。