Android Service啟動流程源碼解析

相信大家都知道威创,Service的啟動方式有兩種:startService和bindService丹泉,今天我們就一起從源碼的角度來學(xué)習(xí)下startService的啟動流程。

啟動一個(gè)Service的方式如下:

    Intent intent = new Intent(MainActivity.this, TestService.class);
    startService(intent);

我們跟進(jìn)去startService方法去看下:

    #ContextWrapper
    @Override
    public ComponentName startService(Intent service) {
        return mBase.startService(service);
    }

可以看到滤祖,ContextWrapper中的startService方法直接調(diào)用到 mBase.startService碌更,mBase是什么呢?它又是在什么時(shí)候被賦值的呢尊剔?其實(shí)mBase就是 ContextImpl實(shí)例爪幻,了解過Activity啟動流程的朋友應(yīng)該很清楚,在Activity實(shí)例創(chuàng)建后须误,會調(diào)用到activity.attach方法挨稿,正是在這個(gè)方法中將當(dāng)前activity實(shí)例對應(yīng)的ContextImpl對象賦值給 mBase成員變量京痢。對Activity啟動流程還不熟悉的朋友可以看下筆者的 《Activity啟動流程源碼解析》:http://www.reibang.com/p/621ae18547b0奶甘;好了,我們接著跟進(jìn)去ContextImpl中的 startService方法:

    #ContextImpl
    @Override
    public ComponentName startService(Intent service) {
        warnIfCallingFromSystemProcess();
        return startServiceCommon(service, false, mUser);
    }

ContextImpl類中的startService方法中直接調(diào)用到 startServiceCommon方法:

    private ComponentName startServiceCommon(Intent service, boolean requireForeground,
            UserHandle user) {
        try {
            validateServiceIntent(service);
            service.prepareToLeaveProcess(this);
            //重點(diǎn)祭椰!
            ComponentName cn = ActivityManager.getService().startService(
                mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
                            getContentResolver()), requireForeground,
                            getOpPackageName(), user.getIdentifier());
            if (cn != null) {
                if (cn.getPackageName().equals("!")) {
                    throw new SecurityException(
                            "Not allowed to start service " + service
                            + " without permission " + cn.getClassName());
                } else if (cn.getPackageName().equals("!!")) {
                    throw new SecurityException(
                            "Unable to start service " + service
                            + ": " + cn.getClassName());
                } else if (cn.getPackageName().equals("?")) {
                    throw new IllegalStateException(
                            "Not allowed to start service " + service + ": " + cn.getClassName());
                }
            }
            return cn;
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

可以看到臭家,在 startServiceCommon方法中直接調(diào)用到 ActivityManager.getService().startService方法疲陕,和Activity的啟動流程一致,這里是由客戶端進(jìn)程向SystemServer進(jìn)程發(fā)起的一次單向IPC操作钉赁,最終調(diào)用到 ActivityManagerService類的startService方法蹄殃,我們跟進(jìn)去看下:

    #ActivityManagerService
    @Override
    public ComponentName startService(IApplicationThread caller, Intent service,
            String resolvedType, boolean requireForeground, String callingPackage, int userId)
            throws TransactionTooLargeException {
        enforceNotIsolatedCaller("startService");
        // Refuse possible leaked file descriptors
        if (service != null && service.hasFileDescriptors() == true) {
            throw new IllegalArgumentException("File descriptors passed in Intent");
        }

        if (callingPackage == null) {
            throw new IllegalArgumentException("callingPackage cannot be null");
        }

        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
                "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
        synchronized(this) {
            final int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            ComponentName res;
            try {
                //重點(diǎn)!
                res = mServices.startServiceLocked(caller, service,
                        resolvedType, callingPid, callingUid,
                        requireForeground, callingPackage, userId);
            } finally {
                Binder.restoreCallingIdentity(origId);
            }
            return res;
        }
    }

在ActivityManagerService的startService方法中橄霉,直接調(diào)用到 mServices.startServiceLocked方法窃爷,mServices對象的類型為ActiveServices,簡單來講姓蜂,ActiveServices是一個(gè)輔助AMS進(jìn)行Service管理的類按厘,包括Service的啟動、綁定和停止等钱慢。我們跟進(jìn)去mServices.startServiceLocked方法看下:

    #ActiveServices
    ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
            int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
            throws TransactionTooLargeException {

        ...
        //重點(diǎn)
        ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
        return cmp;
    }

    ...

    ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
            boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
        ServiceState stracker = r.getTracker();
        if (stracker != null) {
            stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
        }
        r.callStart = false;
        synchronized (r.stats.getBatteryStats()) {
            r.stats.startRunningLocked();
        }

        //重點(diǎn)逮京!
        String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
        if (error != null) {
            return new ComponentName("!!", error);
        }

        if (r.startRequested && addToStarting) {
            boolean first = smap.mStartingBackground.size() == 0;
            smap.mStartingBackground.add(r);
            r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
            if (DEBUG_DELAYED_SERVICE) {
                RuntimeException here = new RuntimeException("here");
                here.fillInStackTrace();
                Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
            } else if (DEBUG_DELAYED_STARTS) {
                Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
            }
            if (first) {
                smap.rescheduleDelayedStartsLocked();
            }
        } else if (callerFg || r.fgRequired) {
            smap.ensureNotStartingBackgroundLocked(r);
        }

        return r.name;
    }

    ...

     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
            boolean whileRestarting, boolean permissionsReviewRequired)
            throws TransactionTooLargeException {

        ...

        if (app != null && app.thread != null) {
                try {
                    app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
                    //重點(diǎn)!J懒棉!
                    realStartServiceLocked(r, app, execInFg);
                    return null;
                } catch (TransactionTooLargeException e) {
                    throw e;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting service " + r.shortName, e);
                }

                // If a dead object exception was thrown -- fall through to
                // restart the application.
            }

        ...
    }

可以看到最終是調(diào)用到 realStartServiceLocked方法,從名字上看览绿,這個(gè)方法應(yīng)該是真正啟動一個(gè)Service策严,我們跟進(jìn)去看下:

private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
     
        ...
 
        //標(biāo)記當(dāng)前Service對象是否成功創(chuàng)建
        boolean created = false;
        try {
            
            synchronized (r.stats.getBatteryStats()) {
                r.stats.startLaunchedLocked();
            }
            mAm.notifyPackageUse(r.serviceInfo.packageName,
                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
            //1.發(fā)起SystemServer進(jìn)程到客戶端進(jìn)程的單向IPC操作,創(chuàng)建Service對象并調(diào)用其onCreate方法
            app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                    app.repProcState);
            r.postNotification();
            created = true;
        } catch (DeadObjectException e) {
            Slog.w(TAG, "Application dead when creating service " + r);
            mAm.appDiedLocked(app);
            throw e;
        } finally {
            if (!created) {
                // Keep the executeNesting count accurate.
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);

                // Cleanup.
                if (newService) {
                    app.services.remove(r);
                    r.app = null;
                }

                // Retry.
                if (!inDestroying) {
                    scheduleServiceRestartLocked(r, false);
                }
            }
        }

        if (r.whitelistManager) {
            app.whitelistManager = true;
        }

        requestServiceBindingsLocked(r, execInFg);

        updateServiceClientActivitiesLocked(app, null, true);

        //2.同樣為IPC操作饿敲,最終調(diào)用到Service對象的onStartCommand方法
        sendServiceArgsLocked(r, execInFg, true);

        ...
    }

上述代碼重點(diǎn)部分已經(jīng)做了標(biāo)注妻导,我們首先來看下 1 處,可以看到 1 處調(diào)用到app.thread.scheduleCreateService方法怀各,由SystemServer進(jìn)程向客戶端進(jìn)程發(fā)起單向IPC操作倔韭,最終調(diào)用到 ApplicationThread 的scheduleCreateService方法,我們跟進(jìn)去看下:

     public final void scheduleCreateService(IBinder token,
                ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
            updateProcessState(processState, false);
            CreateServiceData s = new CreateServiceData();
            s.token = token;
            s.info = info;
            s.compatInfo = compatInfo;

            sendMessage(H.CREATE_SERVICE, s);
        }

我們都知道ApplicationThread為SystemServer進(jìn)程到客戶端進(jìn)程單向通信對應(yīng)的Binder實(shí)現(xiàn)類瓢对,類中的方法都是運(yùn)行在客戶端的Binder線程池中寿酌,所以在scheduleCreateService方法的最后調(diào)用到sendMessage方法,由mH(Handler實(shí)例)發(fā)送了一條CREATE_SERVICE 類型的Message硕蛹,最終調(diào)用到 ActivityThread類的 handleCreateService方法醇疼,我們跟進(jìn)去看下:

    private void handleCreateService(CreateServiceData data) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();

        LoadedApk packageInfo = getPackageInfoNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
            //1.通過類加載器創(chuàng)建Service實(shí)例
            java.lang.ClassLoader cl = packageInfo.getClassLoader();
            service = (Service) cl.loadClass(data.info.name).newInstance();
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to instantiate service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }

        try {
            if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
            //2.創(chuàng)建ContextImpl實(shí)例
            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
            context.setOuterContext(service);
            //3.獲取到當(dāng)前Application實(shí)例
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            //4.調(diào)用當(dāng)前Service對象的attach方法,進(jìn)行關(guān)聯(lián)操作
            service.attach(context, this, data.info.name, data.token, app,
                    ActivityManager.getService());
            //5.調(diào)用當(dāng)前Service對象的onCreate方法
            service.onCreate();
            //6.將當(dāng)前Service對象添加到mServices中
            mServices.put(data.token, service);
            try {
                ActivityManager.getService().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to create service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }
    }

可以看到在 handleCreateService方法中完成了Service對象的創(chuàng)建以及其 onCreate生命周期方法的調(diào)用妓美。

好了僵腺,我們回到 realStartServiceLocked方法的 2 處,繼續(xù)向下分析壶栋,可以看到 2 處調(diào)用到 sendServiceArgsLocked方法辰如,我們跟進(jìn)去看下:

    #ActiveServices
    private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
            boolean oomAdjusted) throws TransactionTooLargeException {

      ...
   
      try {
            //重點(diǎn)
            r.app.thread.scheduleServiceArgs(r, slice);
        } catch (TransactionTooLargeException e) {
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
                    + " args, first: " + args.get(0).args);
            Slog.w(TAG, "Failed delivering service starts", e);
            caughtException = e;
        } catch (RemoteException e) {
            // Remote process gone...  we'll let the normal cleanup take care of this.
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
            Slog.w(TAG, "Failed delivering service starts", e);
            caughtException = e;
        } catch (Exception e) {
            Slog.w(TAG, "Unexpected exception", e);
            caughtException = e;
        }

        ...
    }

在sendServiceArgsLocked方法中調(diào)用到 r.app.thread.scheduleServiceArgs方法,同樣為SystemServer進(jìn)程到應(yīng)用程序進(jìn)程的單向IPC操作贵试,最終調(diào)用到 ApplicationThread的scheduleServiceArgs方法琉兜,我們跟進(jìn)去看下:

    #ApplicationThread
    public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
            List<ServiceStartArgs> list = args.getList();

            for (int i = 0; i < list.size(); i++) {
                ServiceStartArgs ssa = list.get(i);
                ServiceArgsData s = new ServiceArgsData();
                s.token = token;
                s.taskRemoved = ssa.taskRemoved;
                s.startId = ssa.startId;
                s.flags = ssa.flags;
                s.args = ssa.args;

                sendMessage(H.SERVICE_ARGS, s);
            }
        }

我們可以看到凯正,scheduleServiceArgs方法中發(fā)送了一條 SERVICE_ARGS類型的Message,最終調(diào)用到 ActivityThread類的 handleServiceArgs方法豌蟋,我們跟進(jìn)去看下:

   #ActivityThread
   private void handleServiceArgs(ServiceArgsData data) {
        //1.獲取到當(dāng)前Service對象
        Service s = mServices.get(data.token);
        if (s != null) {
            try {
                if (data.args != null) {
                    data.args.setExtrasClassLoader(s.getClassLoader());
                    data.args.prepareToEnterProcess();
                }
                int res;
                if (!data.taskRemoved) {
                    //2.重點(diǎn)廊散,調(diào)用到當(dāng)前Service對象的 onStartCommand方法
                    res = s.onStartCommand(data.args, data.flags, data.startId);
                } else {
                    s.onTaskRemoved(data.args);
                    res = Service.START_TASK_REMOVED_COMPLETE;
                }

                QueuedWork.waitToFinish();

                try {
                    ActivityManager.getService().serviceDoneExecuting(
                            data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
                } catch (RemoteException e) {
                    throw e.rethrowFromSystemServer();
                }
                ensureJitEnabled();
            } catch (Exception e) {
                if (!mInstrumentation.onException(s, e)) {
                    throw new RuntimeException(
                            "Unable to start service " + s
                            + " with " + data.args + ": " + e.toString(), e);
                }
            }
        }
    }

可以看到在 handleServiceArgs方法的 2 處調(diào)用到當(dāng)前 Service對象的 onStartCommand方法。

到這里梧疲,Service的啟動流程就分析完畢了允睹。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市幌氮,隨后出現(xiàn)的幾起案子缭受,更是在濱河造成了極大的恐慌,老刑警劉巖该互,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件米者,死亡現(xiàn)場離奇詭異,居然都是意外死亡宇智,警方通過查閱死者的電腦和手機(jī)蔓搞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來随橘,“玉大人喂分,你說我怎么就攤上這事』幔” “怎么了妻顶?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蜒车。 經(jīng)常有香客問我,道長幔嗦,這世上最難降的妖魔是什么酿愧? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮邀泉,結(jié)果婚禮上嬉挡,老公的妹妹穿的比我還像新娘。我一直安慰自己汇恤,他們只是感情好庞钢,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著因谎,像睡著了一般基括。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上财岔,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天风皿,我揣著相機(jī)與錄音河爹,去河邊找鬼。 笑死桐款,一個(gè)胖子當(dāng)著我的面吹牛咸这,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播魔眨,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼媳维,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了遏暴?” 一聲冷哼從身側(cè)響起侄刽,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拓挥,沒想到半個(gè)月后唠梨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡侥啤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年当叭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片盖灸。...
    茶點(diǎn)故事閱讀 38,039評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚁鳖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出赁炎,到底是詐尸還是另有隱情醉箕,我是刑警寧澤,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布徙垫,位于F島的核電站讥裤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏姻报。R本人自食惡果不足惜己英,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望吴旋。 院中可真熱鬧损肛,春花似錦、人聲如沸荣瑟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽笆焰。三九已至劫谅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背同波。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工鳄梅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人未檩。 一個(gè)月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓戴尸,卻偏偏與公主長得像,于是被迫代替她去往敵國和親冤狡。 傳聞我的和親對象是個(gè)殘疾皇子孙蒙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評論 2 345

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