Android 10 CarService

自己看抬旺,如果不對(duì),請指出亿汞!


image.jpeg

啟動(dòng)流程

image.png
framewrok/base/services/java/com/android/server/SystemServer.java

public final class SystemServer {

    public static void main(String[] args) {
        // setp 1 
        new SystemServer().run();
    }
    
    private void run() {
        // setp 2 啟動(dòng)一系列服務(wù)
        startOtherServices();
    }
    
    private void startOtherServices() {
        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
            traceBeginAndSlog("StartCarServiceHelperService");
            // setp 3 
            // 此處由ServiceManager啟動(dòng)CarServiceHelperService
            mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
            traceEnd();
        }
    }
}
framework/base/services/core/java/com/android/server/SystemServiceManager.java

public class SystemServiceManager {

    @SuppressWarnings("unchecked")
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            // step 4
            // 通過類加載器直接獲取CarServiceHelperService的class對(duì)象
            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);
        }
        // setp 5 執(zhí)行重載函數(shù)
        return startService(serviceClass);
    }

    @SuppressWarnings("unchecked")
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            // step 6 通過反射獲取CarServiceHelperService實(shí)例對(duì)象 
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            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 {
            // step 7 都是繼承SystemService的徘跪,并且執(zhí)行onStart函數(shù)
            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");
    }


}
framework/opt/car/services/src/com/android/internal/car/CarServiceHelperService.java

// 繼承自SystemService
public class CarServiceHelperService extends SystemService {

    @Override
    public void onStart() {
        Intent intent = new Intent();
        intent.setPackage("com.android.car");
        intent.setAction(CAR_SERVICE_INTERFACE);
        // step 8 綁定CarService
        if (!getContext().bindServiceAsUser(intent, mCarServiceConnection, Context.BIND_AUTO_CREATE,
                UserHandle.SYSTEM)) {
            Slog.wtf(TAG, "cannot start car service");
        }
        System.loadLibrary("car-framework-service-jni");
    }
    
    private final ServiceConnection mCarServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            if (DBG) {
                Slog.d(TAG, "onServiceConnected:" + iBinder);
            }
            // step 15 收到CarService的binder對(duì)象
            handleCarServiceConnection(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            handleCarServiceCrash();
        }
    };

    private void handleCarServiceConnection(IBinder iBinder) {
        int lastSwitchedUser;
        boolean systemBootCompleted;
        synchronized (mLock) {
            if (mCarService == iBinder) {
                return; // already connected.
            }
            if (mCarService != null) {
                Slog.i(TAG, "car service binder changed, was:" + mCarService
                        + " new:" + iBinder);
            }
            mCarService = iBinder;
            lastSwitchedUser = mLastSwitchedUser;
            systemBootCompleted = mSystemBootCompleted;
        }
        Slog.i(TAG, "**CarService connected**");
        
        // step 16
        sendSetCarServiceHelperBinderCall();
        if (systemBootCompleted) {
            notifyAllUnlockedUsers();
        }
        if (lastSwitchedUser != UserHandle.USER_NULL) {
            sendSwitchUserBindercall(lastSwitchedUser);
        }
    }


    private void sendSetCarServiceHelperBinderCall() {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(CAR_SERVICE_INTERFACE);
        data.writeStrongBinder(mHelper.asBinder());
        // void setCarServiceHelper(in IBinder helper)
        // step 17 ICAR_CALL_SET_CAR_SERVICE_HELPER代表調(diào)用ICar.aidl的第一個(gè)函數(shù)
        sendBinderCallToCarService(data, ICAR_CALL_SET_CAR_SERVICE_HELPER);
    }

    private void sendBinderCallToCarService(Parcel data, int callNumber) {
        // Cannot depend on ICar which is defined in CarService, so handle binder call directly
        // instead.
        IBinder carService;
        synchronized (mLock) {
            carService = mCarService;
        }
        try {
            // step 18 ICarServiceHelperImpl對(duì)象讳推,ICarServiceHelperImpl是內(nèi)部類艾船,和CarService進(jìn)行雙向通信使用
            carService.transact(IBinder.FIRST_CALL_TRANSACTION + callNumber,
                    data, null, Binder.FLAG_ONEWAY);
        } catch (RemoteException e) {
            Slog.w(TAG, "RemoteException from car service", e);
            handleCarServiceCrash();
        } finally {
            data.recycle();
        }
    }

}
packages/services/Car/service/src/com/android/car/CarService.java

// 是一個(gè)系統(tǒng)進(jìn)程葵腹,實(shí)際上是一個(gè)APK
public class CarService extends Service {

    @Override
    public void onCreate() {
        Log.i(CarLog.TAG_SERVICE, "Service onCreate");
        mCanBusErrorNotifier = new CanBusErrorNotifier(this /* context */);
        mVehicle = getVehicle();

        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);
        
        // step 9 獲取ICarImpl
        mICarImpl = new ICarImpl(this,
                mVehicle,
                SystemInterface.Builder.defaultSystemInterface(this).build(),
                mCanBusErrorNotifier,
                mVehicleInterfaceName);
        // step 10
        mICarImpl.init();

        linkToDeath(mVehicle, mVehicleDeathRecipient);

        ServiceManager.addService("car_service", mICarImpl);
        ServiceManager.addService("car_stats", mICarImpl.getStatsService());
        SystemProperties.set("boot.car_service_created", "1");
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // step 14 CarService中的服務(wù)都初始化后高每,將ICarImpl返回給CarServiceHelperService的ServiceConnection中
        return mICarImpl;
    }

}
packages/services/Car/service/src/com/android/car/ICarImpl.java

// 實(shí)現(xiàn)了接口ICar.aidl的功能
public class ICarImpl extends ICar.Stub {
    
    public ICarImpl(Context serviceContext, IVehicle vehicle, SystemInterface systemInterface,
            CanBusErrorNotifier errorNotifier, String vehicleInterfaceName) {
        mContext = serviceContext;
        mSystemInterface = systemInterface;
        mHal = new VehicleHal(serviceContext, vehicle);
        mVehicleInterfaceName = vehicleInterfaceName;
        mUserManagerHelper = new CarUserManagerHelper(serviceContext);
        final Resources res = mContext.getResources();
        final int maxRunningUsers = res.getInteger(
                com.android.internal.R.integer.config_multiuserMaxRunningUsers);
        mCarUserService = new CarUserService(serviceContext, mUserManagerHelper,
                ActivityManager.getService(), maxRunningUsers);
        mSystemActivityMonitoringService = new SystemActivityMonitoringService(serviceContext);
        mCarPowerManagementService = new CarPowerManagementService(mContext, mHal.getPowerHal(),
                systemInterface, mUserManagerHelper);
        mCarUserNoticeService = new CarUserNoticeService(serviceContext);
        mCarPropertyService = new CarPropertyService(serviceContext, mHal.getPropertyHal());
        mCarDrivingStateService = new CarDrivingStateService(serviceContext, mCarPropertyService);
        mCarUXRestrictionsService = new CarUxRestrictionsManagerService(serviceContext,
                mCarDrivingStateService, mCarPropertyService);
        mCarPackageManagerService = new CarPackageManagerService(serviceContext,
                mCarUXRestrictionsService,
                mSystemActivityMonitoringService,
                mUserManagerHelper);
        mPerUserCarServiceHelper = new PerUserCarServiceHelper(serviceContext);
        mCarBluetoothService = new CarBluetoothService(serviceContext, mPerUserCarServiceHelper);
        mCarInputService = new CarInputService(serviceContext, mHal.getInputHal());
        mCarProjectionService = new CarProjectionService(
                serviceContext, null /* handler */, mCarInputService, mCarBluetoothService);
        mGarageModeService = new GarageModeService(mContext);
        mAppFocusService = new AppFocusService(serviceContext, mSystemActivityMonitoringService);
        mCarAudioService = new CarAudioService(serviceContext);
        mCarNightService = new CarNightService(serviceContext, mCarPropertyService);
        mFixedActivityService = new FixedActivityService(serviceContext);
        mInstrumentClusterService = new InstrumentClusterService(serviceContext,
                mAppFocusService, mCarInputService);
        mSystemStateControllerService = new SystemStateControllerService(
                serviceContext, mCarAudioService, this);
        mCarStatsService = new CarStatsService(serviceContext);
        mVmsBrokerService = new VmsBrokerService();
        mVmsClientManager = new VmsClientManager(
                // CarStatsService needs to be passed to the constructor due to HAL init order
                serviceContext, mCarStatsService, mCarUserService, mVmsBrokerService,
                mHal.getVmsHal());
        mVmsSubscriberService = new VmsSubscriberService(
                serviceContext, mVmsBrokerService, mVmsClientManager, mHal.getVmsHal());
        mVmsPublisherService = new VmsPublisherService(
                serviceContext, mCarStatsService, mVmsBrokerService, mVmsClientManager);
        mCarDiagnosticService = new CarDiagnosticService(serviceContext, mHal.getDiagnosticHal());
        mCarStorageMonitoringService = new CarStorageMonitoringService(serviceContext,
                systemInterface);
        mCarConfigurationService =
                new CarConfigurationService(serviceContext, new JsonReaderImpl());
        mCarLocationService = new CarLocationService(mContext, mUserManagerHelper);
        mCarTrustedDeviceService = new CarTrustedDeviceService(serviceContext);
        mCarMediaService = new CarMediaService(serviceContext);
        mCarBugreportManagerService = new CarBugreportManagerService(serviceContext);
        mAirplaneModeService = new AirplaneModeService(serviceContext);

        // step 11 初始化了一堆服務(wù),并且添加到了CarLocalServices践宴,并且對(duì)外提供getService函數(shù)
        CarLocalServices.addService(CarPowerManagementService.class, mCarPowerManagementService);
        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);
        // Be careful with order. Service depending on other service should be inited later.
        List<CarServiceBase> allServices = new ArrayList<>();
        allServices.add(mCarUserService);
        allServices.add(mSystemActivityMonitoringService);
        allServices.add(mCarPowerManagementService);
        allServices.add(mCarPropertyService);
        allServices.add(mCarDrivingStateService);
        allServices.add(mCarUXRestrictionsService);
        allServices.add(mCarPackageManagerService);
        allServices.add(mCarInputService);
        allServices.add(mGarageModeService);
        allServices.add(mCarUserNoticeService);
        allServices.add(mAppFocusService);
        allServices.add(mCarAudioService);
        allServices.add(mCarNightService);
        allServices.add(mFixedActivityService);
        allServices.add(mInstrumentClusterService);
        allServices.add(mSystemStateControllerService);
        allServices.add(mPerUserCarServiceHelper);
        allServices.add(mCarBluetoothService);
        allServices.add(mCarProjectionService);
        allServices.add(mCarDiagnosticService);
        allServices.add(mCarStorageMonitoringService);
        allServices.add(mCarConfigurationService);
        allServices.add(mVmsClientManager);
        allServices.add(mVmsSubscriberService);
        allServices.add(mVmsPublisherService);
        allServices.add(mCarTrustedDeviceService);
        allServices.add(mCarMediaService);
        allServices.add(mCarLocationService);
        allServices.add(mCarBugreportManagerService);
        allServices.add(mAirplaneModeService);
        
        // step 12 通過getService獲取對(duì)象鲸匿,典型工廠模式,這些服務(wù)都繼承CarServiceBase阻肩,mAllServices是CarServiceBase的一個(gè)數(shù)組带欢,保存在當(dāng)前類中
        mAllServices = allServices.toArray(new CarServiceBase[allServices.size()]);
    }
    
    
    @MainThread
    void init() {
        mBootTiming = new TimingsTraceLog(VHAL_TIMING_TAG, Trace.TRACE_TAG_HAL);
        traceBegin("VehicleHal.init");
        mHal.init();
        traceEnd();
        traceBegin("CarService.initAllServices");
        for (CarServiceBase service : mAllServices) {
            // step 13 所有業(yè)務(wù)服務(wù)執(zhí)行初始化
            service.init();
        }
        traceEnd();
        mSystemInterface.reconfigureSecondaryDisplays();
    }


    @Override
    public void setCarServiceHelper(IBinder helper) {
        assertCallingFromSystemProcess();
        synchronized (this) {
            // step 19 拿到CarServiceHelperService的ICarHelperImpl對(duì)象進(jìn)行雙向通信
            mICarServiceHelper = ICarServiceHelper.Stub.asInterface(helper);
            mSystemInterface.setCarServiceHelper(mICarServiceHelper);
        }
    }
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市烤惊,隨后出現(xiàn)的幾起案子乔煞,更是在濱河造成了極大的恐慌,老刑警劉巖柒室,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件以政,死亡現(xiàn)場離奇詭異饼记,居然都是意外死亡羔巢,警方通過查閱死者的電腦和手機(jī)伙狐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門蕴忆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來躏精,“玉大人卫枝,你說我怎么就攤上這事惩系】陶铮” “怎么了防楷?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長则涯。 經(jīng)常有香客問我复局,道長,這世上最難降的妖魔是什么粟判? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任亿昏,我火速辦了婚禮,結(jié)果婚禮上档礁,老公的妹妹穿的比我還像新娘角钩。我一直安慰自己,他們只是感情好呻澜,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布递礼。 她就那樣靜靜地躺著,像睡著了一般羹幸。 火紅的嫁衣襯著肌膚如雪脊髓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天栅受,我揣著相機(jī)與錄音将硝,去河邊找鬼恭朗。 笑死,一個(gè)胖子當(dāng)著我的面吹牛袋哼,可吹牛的內(nèi)容都是我干的冀墨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼涛贯,長吁一口氣:“原來是場噩夢啊……” “哼诽嘉!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起弟翘,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤虫腋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后稀余,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體悦冀,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年睛琳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了盒蟆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡师骗,死狀恐怖历等,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情辟癌,我是刑警寧澤寒屯,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站黍少,受9級(jí)特大地震影響寡夹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜厂置,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一菩掏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧昵济,春花似錦患蹂、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至醉顽,卻和暖如春沼溜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背游添。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工系草, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留通熄,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓找都,卻偏偏與公主長得像唇辨,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子能耻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容