美文网首页android之基础学习攻克
Service相关流程学习-Unbouned Start Ser

Service相关流程学习-Unbouned Start Ser

作者: weiinter105 | 来源:发表于2018-11-25 18:15 被阅读0次

    Service启动-Unbounded Service

    即通过startService启动的Service服务
    若Service没有启动,甚至Service所在的进程都没有启动,那么AMS将负责启动Service所在的进程,然后通过反射创建出Service。
    当Service创建完毕后,AMS负责回调Service生命周期中的onCreate函数。
    待Service完成启动后,AMS将进一步回调Service的onStartCommand函数,将Intent递交给其处理。

    若Service已经启动了,那么在之后的通信中,当客户端再次调用startService传递Intent给Service时, AMS仅会回调Service的onStartCommand函数进行处理。

    ContextImpl#startService

    1468    @Override
    1469    public ComponentName startService(Intent service) {
    1470        warnIfCallingFromSystemProcess();
    1471        return startServiceCommon(service, false, mUser);
    1472    }
    

    ContextImpl#startServiceCommon

    1496    private ComponentName startServiceCommon(Intent service, boolean requireForeground,
    1497            UserHandle user) {
    1498        try {
    1499            validateServiceIntent(service);
    1500            service.prepareToLeaveProcess(this);
    1501            ComponentName cn = ActivityManager.getService().startService(
    1502                mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
    1503                            getContentResolver()), requireForeground,
    1504                            getOpPackageName(), user.getIdentifier());
    1505            if (cn != null) {
    1506                if (cn.getPackageName().equals("!")) {
    1507                    throw new SecurityException(
    1508                            "Not allowed to start service " + service
    1509                            + " without permission " + cn.getClassName());
    1510                } else if (cn.getPackageName().equals("!!")) {
    1511                    throw new SecurityException(
    1512                            "Unable to start service " + service
    1513                            + ": " + cn.getClassName());
    1514                } else if (cn.getPackageName().equals("?")) {
    1515                    throw new IllegalStateException(
    1516                            "Not allowed to start service " + service + ": " + cn.getClassName());
    1517                }
    1518            }
    1519            return cn;
    1520        } catch (RemoteException e) {
    1521            throw e.rethrowFromSystemServer();
    1522        }
    1523    }
    

    ActivityManagerService#startService

    18715    @Override
    18716    public ComponentName startService(IApplicationThread caller, Intent service,
    18717            String resolvedType, boolean requireForeground, String callingPackage, int userId)
    18718            throws TransactionTooLargeException {
    18719        enforceNotIsolatedCaller("startService");
    18720        // Refuse possible leaked file descriptors
    18721        if (service != null && service.hasFileDescriptors() == true) {
    18722            throw new IllegalArgumentException("File descriptors passed in Intent");
    18723        }
    18730
    18731        if (callingPackage == null) {
    18732            throw new IllegalArgumentException("callingPackage cannot be null");
    18733        }
    18734
    18735        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
    18736                "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
    18737        synchronized(this) {
    18738            final int callingPid = Binder.getCallingPid();
    18739            final int callingUid = Binder.getCallingUid();
    18740            final long origId = Binder.clearCallingIdentity();
    18741            ComponentName res;
    18742            try {
    18743                res = mServices.startServiceLocked(caller, service,
    18744                        resolvedType, callingPid, callingUid,
    18745                        requireForeground, callingPackage, userId);
    18746            } finally {
    18747                Binder.restoreCallingIdentity(origId);
    18748            }
    18749            return res;
    18750        }
    18751    }
    

    ActiveServices#startServiceLocked

    358    ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
    359            int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId) // fgRequired 带参数,是否前台Service
    360            throws TransactionTooLargeException {
    361        if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
    362                + " type=" + resolvedType + " args=" + service.getExtras());
    363
    364        final boolean callerFg;
    365        if (caller != null) {
    366            final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);  //找到调用端的ProcessRecord
    367            if (callerApp == null) {
    368                throw new SecurityException(
    369                        "Unable to find app for caller " + caller
    370                        + " (pid=" + callingPid
    371                        + ") when starting service " + service);
    372            }
    373            callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND; //观察调用端是否是前台进程
    374        } else {
    375            callerFg = true;
    376        }
    377
    378        ServiceLookupResult res =
    379            retrieveServiceLocked(service, resolvedType, callingPackage,
    380                    callingPid, callingUid, userId, true, callerFg, false); //检索待启动的Service   isBindExternal为false
    381        if (res == null) {
    382            return null;
    383        }
    384        if (res.record == null) {
    385            return new ComponentName("!", res.permission != null
    386                    ? res.permission : "private to package");
    387        }
    388
    389        ServiceRecord r = res.record;
    390
    391        if (!mAm.mUserController.exists(r.userId)) {
    392            Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
    393            return null;
    394        }
    395
    396        // If this isn't a direct-to-foreground start, check our ability to kick off an
    397        // arbitrary service
    398        if (!r.startRequested && !fgRequired) { //如果启动的不是前台Service,需要做权限校验
    399            // Before going further -- if this app is not allowed to start services in the
    400            // background, then at this point we aren't going to let it period.
    401            final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
    402                 
    403                    // r.appInfo.targetSdkVersion, callingPid, false, false);
    404                    r.appInfo.targetSdkVersion, callingPid, false, false, callingPackage); //观察调用端是否有权限起后台Service
    405
    406            if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
    407                Slog.w(TAG, "Background start not allowed: service "
    408                        + service + " to " + r.name.flattenToShortString()
    409                        + " from pid=" + callingPid + " uid=" + callingUid
    410                        + " pkg=" + callingPackage);
    411                if (allowed == ActivityManager.APP_START_MODE_DELAYED) {
    412                    // In this case we are silently disabling the app, to disrupt as
    413                    // little as possible existing apps.
    414                    return null;
    415                }
    416                // This app knows it is in the new model where this operation is not
    417                // allowed, so tell it what has happened.
    418                UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
    419                return new ComponentName("?", "app is in background uid " + uidRec);
    420            }
    421        }
    422
    423        NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
    424                callingUid, r.packageName, service, service.getFlags(), null, r.userId);
    425
    426        // If permissions need a review before any of the app components can run,
    427        // we do not start the service and launch a review activity if the calling app
    428        // is in the foreground passing it a pending intent to start the service when
    429        // review is completed.
    430        if (mAm.mPermissionReviewRequired) {
    431            if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
    432                    callingUid, service, callerFg, userId)) {
    433                return null;
    434            }
    435        }
    436
    437        if (unscheduleServiceRestartLocked(r, callingUid, false)) { //final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
    141           //Service重新启动时从restart队列移除,看注释是Service crash之后restart
    438            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
    439        }
    440        r.lastActivity = SystemClock.uptimeMillis();
    441        r.startRequested = true;
    442        r.delayedStop = false;
    443        r.fgRequired = fgRequired;
    444        r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
    445                service, neededGrants, callingUid)); //每个startService 对应一个startItem ,自动分配id,与callingUid也有关
    446
    447        final ServiceMap smap = getServiceMapLocked(r.userId); //得到ServiceMap 用于缓存ServiceRecord的
    448        boolean addToStarting = false;
        //addToStarting决定是否将待启动的Service
        //加入到ActiveServices维护的mStartingBackground队列
    
     //如果启动服务的不是前台进程,且也不是前台服务
     //同时服务对应的ServiceRecord中没有记录对应进程的信息(即初次使用)
    449        if (!callerFg && !fgRequired && r.app == null
    //并且user已经启动过其它进程
    450                && mAm.mUserController.hasStartedUserState(r.userId)) {
    451            ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
    //若Service对应的进程未启动,或优先级过低,则有可能需要延迟启动服务
    452            if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
    453                // If this is not coming from a foreground caller, then we may want
    454                // to delay the start if there are already other background services
    455                // that are starting.  This is to avoid process start spam when lots
    456                // of applications are all handling things like connectivity broadcasts.
    457                // We only do this for cached processes, because otherwise an application
    458                // can have assumptions about calling startService() for a service to run
    459                // in its own process, and for that process to not be killed before the
    460                // service is started.  This is especially the case for receivers, which
    461                // may start a service in onReceive() to do some additional work and have
    462                // initialized some global state as part of that.
    463                if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
    464                        + r + " in " + proc);
    465                if (r.delayed) {
    466                    // This service is already scheduled for a delayed start; just leave
    467                    // it still waiting.
    468                    if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
    469                    return r.name; //已经标注delay的Service直接返回,不走下面startServiceInnerLocked逻辑即可
    470                }
    471              
    //若当前用户启动的后台服务数量过多,则延迟启动服务
    472                if (smap.mStartingBackground.size() >= mMaxStartingBackground + mAdditionalBootStartingBackground) {
    473                    // Something else is starting, delay!
    474                    Slog.i(TAG_SERVICE, "Delaying start of: " + r);
    475                    smap.mDelayedStartList.add(r);
    476                    r.delayed = true;
    477                    return r.name; 
    478                }
    479                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
    480                addToStarting = true; //否则将服务加入后台队列
    481            } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) { //服务进程优先级高
    482                // We slightly loosen when we will enqueue this new service as a background
    483                // starting service we are waiting for, to also include processes that are
    484                // currently running other services or receivers.
    485                addToStarting = true;
    486                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    487                        "Not delaying, but counting as bg: " + r);
    488            } else if (DEBUG_DELAYED_STARTS) {
    489                StringBuilder sb = new StringBuilder(128);
    490                sb.append("Not potential delay (state=").append(proc.curProcState)
    491                        .append(' ').append(proc.adjType);
    492                String reason = proc.makeAdjReason();
    493                if (reason != null) {
    494                    sb.append(' ');
    495                    sb.append(reason);
    496                }
    497                sb.append("): ");
    498                sb.append(r.toString());
    499                Slog.v(TAG_SERVICE, sb.toString());
    500            }
    501        } else if (DEBUG_DELAYED_STARTS) {
    502            if (callerFg || fgRequired) {
    503                Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
    504                        + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
    505            } else if (r.app != null) {
    506                Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
    507            } else {
    508                Slog.v(TAG_SERVICE,
    509                        "Not potential delay (user " + r.userId + " not started): " + r);
    510            }
    511        }
    512        //addToStarting这个值应该是判断,后台启动的,后台Service是延迟执行false,还是立即执行true
    513        ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
    514        return cmp;
    515    }
    

    ActiveServices#retrieveServiceLocked

    从userId对应的缓存中查找ServiceRecord,如果没有,构建一个

    1717    private ServiceLookupResult retrieveServiceLocked(Intent service,
    1718            String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
    1719            boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
    1720        ServiceRecord r = null;
    1721        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
    1722                + " type=" + resolvedType + " callingUid=" + callingUid);
    1723         //得到当前的userId
    1724        userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
    1725                ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
    1726
    1727        ServiceMap smap = getServiceMapLocked(userId); //得到userId的ServiceMap   
                     //final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
    1728        final ComponentName comp = service.getComponent();
    1729        if (comp != null) {
    1730            r = smap.mServicesByName.get(comp); //得到要启动的ServiceRecord
    1731            if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
    1732        }
    1733        if (r == null && !isBindExternal) {
    1734            Intent.FilterComparison filter = new Intent.FilterComparison(service);
    1735            r = smap.mServicesByIntent.get(filter); //这是用于隐式启动的吧?还有用吗?
    1736            if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
    1737        }
    1738        if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
    1739                && !callingPackage.equals(r.packageName)) {
    1740            // If an external service is running within its own package, other packages
    1741            // should not bind to that instance.
    1742            r = null;
    1743            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
    1744        }
    1745        if (r == null) { //缓存中查找不到的情况,创建ServiceRecord结构体
    1746            try {
    1747                // TODO: come back and remove this assumption to triage all services
                            //缓存中找不到Service,第一次启动,AMS中还没有缓存,通过PMS查找Manifest文件来查找相应的Service
    1748                ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
    1749                        resolvedType, ActivityManagerService.STOCK_PM_FLAGS
    1750                                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
    1751                        userId, callingUid);
    1752                ServiceInfo sInfo =
    1753                    rInfo != null ? rInfo.serviceInfo : null; //从ResolveInfo中取出ServiceInfo
    1754                if (sInfo == null) {
    1755                    Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
    1756                          ": not found");
    1757                    return null;
    1758                }
    1759                ComponentName name = new ComponentName(
    1760                        sInfo.applicationInfo.packageName, sInfo.name); //找出ComponentName
    1761                if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
                                //针对 FLAG_EXTERNAL_SERVICE,将其改为运行在调用方中                      
    1762                    if (isBindExternal) {
    1763                        if (!sInfo.exported) {
    1764                            throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
    1765                                    " is not exported");
    1766                        }
    1767                        if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
    1768                            throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
    1769                                    " is not an isolatedProcess");
    1770                        }
    1771                        // Run the service under the calling package's application.
    1772                        ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
    1773                                callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
    1774                        if (aInfo == null) {
    1775                            throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
    1776                                    "could not resolve client package " + callingPackage);
    1777                        }
    1778                        sInfo = new ServiceInfo(sInfo);
    1779                        sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
    1780                        sInfo.applicationInfo.packageName = aInfo.packageName;
    1781                        sInfo.applicationInfo.uid = aInfo.uid;
    1782                        name = new ComponentName(aInfo.packageName, name.getClassName());
    1783                        service.setComponent(name);
    1784                    } else {
    1785                        throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
    1786                                name);
    1787                    }
    1788                } else if (isBindExternal) {
    1789                    throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
    1790                            " is not an externalService");
    1791                }
    1792                if (userId > 0) {
                                 //对于多用户而言,每个用户启动的服务,运行于对应用户所在进程组中
                                  //但如果待启动服务为单例的(FLAG_SINGLE_USER),那么该服务还是得运行在系统用户的进程组中
                                   //于是此次将userId置为0                     
    1793                    if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
    1794                            sInfo.name, sInfo.flags)
    1795                            && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
    1796                        userId = 0;
    1797                        smap = getServiceMapLocked(0);
    1798                    }
    1799                    sInfo = new ServiceInfo(sInfo);
                                 //此处使用了userId
    1800                    sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
    1801                }
    1802                r = smap.mServicesByName.get(name);
    1803                if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
    1804                        "Retrieved via pm by intent: " + r);
    1805                if (r == null && createIfNeeded) {
    1806                    final Intent.FilterComparison filter
    1807                            = new Intent.FilterComparison(service.cloneFilter());
    1808                    final ServiceRestarter res = new ServiceRestarter();
    1809                    final BatteryStatsImpl.Uid.Pkg.Serv ss;
    1810                    final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
    1811                    synchronized (stats) {
    1812                        ss = stats.getServiceStatsLocked(
    1813                                sInfo.applicationInfo.uid, sInfo.packageName,
    1814                                sInfo.name);
    1815                    }
                                 //根据sInfo创建出对应的ServiceRecord
    1816                    r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
    1817                    res.setService(r);
    1818                    smap.mServicesByName.put(name, r);
    1819                    smap.mServicesByIntent.put(filter, r); //缓存
    1820
    1821                    // Make sure this component isn't in the pending list.
    1822                    for (int i=mPendingServices.size()-1; i>=0; i--) {
    1823                        final ServiceRecord pr = mPendingServices.get(i);
    1824                        if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
    1825                                && pr.name.equals(name)) {
    1826                            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
    1827                            mPendingServices.remove(i); 
    1828                        }
    1829                    }
    1830                    if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
    1831                }
    1832            } catch (RemoteException ex) {
    1833                // pm is in same process, this will never happen.
    1834            }
    1835        }
    1836        if (r != null) {
    1838            r.callerPackage = callingPackage;
    1839            if (mAm.checkComponentPermission(r.permission,
    1840                    callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
    1841                if (!r.exported) {
    1842                    Slog.w(TAG, "Permission Denial: Accessing service " + r.name
    1843                            + " from pid=" + callingPid
    1844                            + ", uid=" + callingUid
    1845                            + " that is not exported from uid " + r.appInfo.uid);
    1846                    return new ServiceLookupResult(null, "not exported from uid "
    1847                            + r.appInfo.uid);
    1848                }
    1849                Slog.w(TAG, "Permission Denial: Accessing service " + r.name
    1850                        + " from pid=" + callingPid
    1851                        + ", uid=" + callingUid
    1852                        + " requires " + r.permission);
    1853                return new ServiceLookupResult(null, r.permission);
    1854            } else if (r.permission != null && callingPackage != null) {
    1855                final int opCode = AppOpsManager.permissionToOpCode(r.permission);
    1856                if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
    1857                        opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
    1858                    Slog.w(TAG, "Appop Denial: Accessing service " + r.name
    1859                            + " from pid=" + callingPid
    1860                            + ", uid=" + callingUid
    1861                            + " requires appop " + AppOpsManager.opToName(opCode));
    1862                    return null;
    1863                }
    1864            }
    1865
    1866            if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
    1867                    resolvedType, r.appInfo)) {
    1868                return null;
    1869            }
    1870            return new ServiceLookupResult(r, null); //返回ServiceRecord或者null
    1871        }
    1872        return null;
    1873    }
    

    到前面为止,做了从AMS缓存中找ServiceRecord,没有新增一个放入缓存,设置上面得到或新增的ServiceRecord;检查后台启动的,后台Service的权限,是否需要delay

    ActiveServices#startServiceInnerLocked

    561    ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
    562            boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
    563        ServiceState stracker = r.getTracker();
    564        if (stracker != null) {
    565            stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
    566        }
    567        r.callStart = false;
    568        synchronized (r.stats.getBatteryStats()) {
    569            r.stats.startRunningLocked();
    570        }
    571        String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false); //主要工作通过bringUpServiceLocked函数完成
    572        if (error != null) {
    573            return new ComponentName("!!", error);
    574        }
    575
    576        if (r.startRequested && addToStarting) { //需要加到后台服务队列中,一旦作为后台服务,就可能会与delay Service有牵扯
    577            boolean first = smap.mStartingBackground.size() == 0;
    578            smap.mStartingBackground.add(r); //addToStarting为true,将r加入mStartingBackground队列
    579            r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT; //为Service设置后台超时时间
    580            if (DEBUG_DELAYED_SERVICE) {
    581                RuntimeException here = new RuntimeException("here");
    582                here.fillInStackTrace();
    583                Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
    584            } else if (DEBUG_DELAYED_STARTS) {
    585                Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
    586            }
    587            if (first) {
                         /first为true,说明之前mStartingBackground中的Service处理完毕
                        //调用smap的rescheduleDelayedStarts函数
    588                smap.rescheduleDelayedStartsLocked();
    589            }
    590        } else if (callerFg || r.fgRequired) {
             //若当前Service被后台进程启动过,现在重新被前台进程启动
            //则将其从mStartingBackground中移除,并调用rescheduleDelayedStarts函数(后台服务少了一个,故可能可以继续处理等待的延迟服务)延迟服务与后台服务有关
            //若mDelayedStartList存在该服务的记录,移除对应的信息
    591            smap.ensureNotStartingBackgroundLocked(r);
    592        }
    593
    594        return r.name;
    595    }
    
    243        void ensureNotStartingBackgroundLocked(ServiceRecord r) {
    244            if (mStartingBackground.remove(r)) { //若ServiceRecord能在mStartingBackground被找到 (这里的ServiceRecord肯定是从ServiceMap的缓存中取出来的,所以添加了StartItem之后也可以被找到)
    245                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    246                        "No longer background starting: " + r);
    247                rescheduleDelayedStartsLocked(); //调用rescheduleDelayedStartsLocked
    248            }
    249            if (mDelayedStartList.remove(r)) {  //若mDelayedStartList存在该服务的记录,移除对应的信息
    250                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
    251            }
    252        }
    

    ActiveServices#rescheduleDelayedStartsLocked
    只要后台服务多或者最前的后台服务超时少了就会调用,用来试探是否有机会执行delay list里面的Service

    254        void rescheduleDelayedStartsLocked() {
    255            removeMessages(MSG_BG_START_TIMEOUT); //执行MSG_BG_START_TIMEOUT消息时会调用这个函数,所以执行时第一步就是将Message remove
    256            final long now = SystemClock.uptimeMillis();
    257            for (int i=0, N=mStartingBackground.size(); i<N; i++) {
    258                ServiceRecord r = mStartingBackground.get(i);
    259                if (r.startingBgTimeout <= now) {
    260                    Slog.i(TAG, "Waited long enough for: " + r);
    261                    mStartingBackground.remove(i); //如果是因为有后台Service超时发送MSG_BG_START_TIMEOUT导致调用的rescheduleDelayedStartsLocked,则将超时的后台消息全部移除,不再执行
    262                    N--;
    263                    i--;
    264                }
    265            }
    266            while (mDelayedStartList.size() > 0
    267                    
    268                    && mStartingBackground.size() < mMaxStartingBackground + mAdditionalBootStartingBackground) {
                         //这里的条件其实最关键,一般就是后台服务少到一定程度才开始在rescheduleDelayedStartsLocked处理delay service和delay广播;而后台服务怎么样才会减少呢 1.Service被kill 2.stopService? 3.超时
                         //如果后台服务很多,一直要等到第一个后台服务超时,发送了time out消息;又调用一次,看看是否后台服务数量满足要求了,不满足继续设置下一个超时消息;
                          //相当于只要后台数量很多,不管怎么样都会执行到rescheduleDelayedStartsLocked,通过发送消息实现了rescheduleDelayedStartsLocked的循环调用(系统中感觉交常见,但很聪明)
                          //直到后台服务数量为0或减少调用的rescheduleDelayedStartsLocked,此时后台服务不多,满足数量条件,则取出第一个延迟队列中的Service开始执行
    269                ServiceRecord r = mDelayedStartList.remove(0);
    270                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    271                        "REM FR DELAY LIST (exec next): " + r);
    278                if (DEBUG_DELAYED_SERVICE) {
    279                    if (mDelayedStartList.size() > 0) {
    280                        Slog.v(TAG_SERVICE, "Remaining delayed list:");
    281                        for (int i=0; i<mDelayedStartList.size(); i++) {
    282                            Slog.v(TAG_SERVICE, "  #" + i + ": " + mDelayedStartList.get(i));
    283                        }
    284                    }
    285                }
    286                r.delayed = false;
    287                if (r.pendingStarts.size() <= 0) {
    288                    Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
    289                            + " delayedStop=" + r.delayedStop);
    290                    continue;
    291                }
    293
    294                try {
    295                    startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true); //执行延迟的Service
    296                } catch (TransactionTooLargeException e) {
    297                    // Ignore, nobody upstack cares.
    298                }
    299            }
     //跳出while,delay Service执行完了或者根本未进入while循环(只要还有后台服务,就可能调用rescheduleDelayedStartsLocked)
    300            if (mStartingBackground.size() > 0) {
    301                ServiceRecord next = mStartingBackground.get(0);
    302                long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
    303                if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
    304                        + ", can delay others up to " + when);
    305                Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
    306                sendMessageAtTime(msg, when); //若后台服务队列里还有值,取第一个Service,发送一个超时消息
    307            }
    308            
    309            if (mStartingBackground.size() < mMaxStartingBackground + mAdditionalBootStartingBackground) {
    310                mAm.backgroundServicesFinishedLocked(mUserId); //resume delay的广播
    311            }
    312        }
    313    }
    
    236                case MSG_BG_START_TIMEOUT: {
    237                    synchronized (mAm) {
    238                        rescheduleDelayedStartsLocked();
    239                    }
    240                } break;
    

    ActiveServices#bringUpServiceLocked

    回到bringUpServiceLocked,分三种情况处理 1.进程和Service都启动了 2.进程启动了,但Service还没启动 3.进程也没启动

    2194    private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
    2195            boolean whileRestarting, boolean permissionsReviewRequired)
    2196            throws TransactionTooLargeException {
    2197        //Slog.i(TAG, "Bring up service:");
    2198        //r.dump("  ");
    2199
    2200        if (r.app != null && r.app.thread != null) { 
                        //处理Service已经启动的情况,只是发送新的startItem      (发送参数)                                                   
    2201            sendServiceArgsLocked(r, execInFg, false);
    2202            return null;
    2203        }
    2204
    2205        if (!whileRestarting && mRestartingServices.contains(r)) {
    2206            // If waiting for a restart, then do nothing.
    2207            return null;
    2208        }
    2209
    2210        if (DEBUG_SERVICE) {
    2211            Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
    2212        }
    2213
    2214        // We are now bringing the service up, so no longer in the
    2215        // restarting state.
    2216        if (mRestartingServices.remove(r)) {
    2217            clearRestartingIfNeededLocked(r);
    2218        }
    2219
    2220        // Make sure this service is no longer considered delayed, we are starting it now.
    2221        if (r.delayed) { //如果被delay的Service走到这里了,说明开始正式启动了
    2222            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
    2223            getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
    2224            r.delayed = false;
    2225        }
    2226
    2227        // Make sure that the user who owns this service is started.  If not,
    2228        // we don't want to allow it to run.
    2229        if (!mAm.mUserController.hasStartedUserState(r.userId)) {
    2230            String msg = "Unable to launch app "
    2231                    + r.appInfo.packageName + "/"
    2232                    + r.appInfo.uid + " for service "
    2233                    + r.intent.getIntent() + ": user " + r.userId + " is stopped";
    2234            Slog.w(TAG, msg);
    2235            bringDownServiceLocked(r);
    2236            return msg;
    2237        }
    2238
    2239        // Service is now being launched, its package can't be stopped.
    2240        try {
    2241            AppGlobals.getPackageManager().setPackageStoppedState(
    2242                    r.packageName, false, r.userId);
    2243        } catch (RemoteException e) {
    2244        } catch (IllegalArgumentException e) {
    2245            Slog.w(TAG, "Failed trying to unstop package "
    2246                    + r.packageName + ": " + e);
    2247        }
    2248
    2249        final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
    2250        final String procName = r.processName;
    2251        String hostingType = "service";
    2252        ProcessRecord app;
    2253
    2254        if (!isolated) {
                        //Service所在进程
    2255            app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
    2256            if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
    2257                        + " app=" + app);
    2258            if (app != null && app.thread != null) {
    2259                try {
                                 //如果进程已经存在,但此时Service还没有启动
    2260                    app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
    2261                    realStartServiceLocked(r, app, execInFg); //真正启动服务
    2262                    return null;
    2263                } catch (TransactionTooLargeException e) {
    2264                    throw e;
    2265                } catch (RemoteException e) {
    2266                    Slog.w(TAG, "Exception when starting service " + r.shortName, e);
    2267                }
    2268
    2269                // If a dead object exception was thrown -- fall through to
    2270                // restart the application.
    2271            }
    2272        } else {
    2273            // If this service runs in an isolated process, then each time
    2274            // we call startProcessLocked() we will get a new isolated
    2275            // process, starting another process if we are currently waiting
    2276            // for a previous process to come up.  To deal with this, we store
    2277            // in the service any current isolated process it is running in or
    2278            // waiting to have come up.
    2279            app = r.isolatedProc;
    2280            if (WebViewZygote.isMultiprocessEnabled()
    2281                    && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
    2282                hostingType = "webview_service";
    2283            }
    2284        }
    2285
    2286        // Not running -- get it started, and enqueue this service record
    2287        // to be executed when the app comes up.
    2288        if (app == null && !permissionsReviewRequired) {
                              //进程服务也不存在,启动服务进程,将Service保存到mPendingServices中,这样就可以等到进程启动后再启动Service
    2289            if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
    2291                        //hostingType, r.name, false, isolated, false)) == null) {
    2292                        hostingType, r.name, false, isolated, false, r.callerPackage)) == null) {
    2293                String msg = "Unable to launch app "
    2294                        + r.appInfo.packageName + "/"
    2295                        + r.appInfo.uid + " for service "
    2296                        + r.intent.getIntent() + ": process is bad";
    2297                Slog.w(TAG, msg);
    2298                bringDownServiceLocked(r);
    2299                return msg;
    2300            }
    2301            if (isolated) {
    2302                r.isolatedProc = app;
    2303            }
    2304        }
    2305
    2306        if (r.fgRequired) { //与前台服务相关逻辑
    2307            if (DEBUG_FOREGROUND_SERVICE) {
    2308                Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
    2309                        + " for fg-service launch");
    2310            }
    2311            mAm.tempWhitelistUidLocked(r.appInfo.uid,
    2312                    SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
    2313        }
    2314
    2315        if (!mPendingServices.contains(r)) {
    2316            mPendingServices.add(r); //保存待启动的服务,当服务所在进程真正启动时,再启动服务
    2317        }
    2318
    2319        if (r.delayedStop) {
                        //服务还未完成启动,就收到结束请求时,会直接停止该服务
    2320            // Oh and hey we've already been asked to stop!
    2321            r.delayedStop = false;
    2322            if (r.startRequested) { 
    2323                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    2324                        "Applying delayed stop (in bring up): " + r);
    2325                stopServiceLocked(r);
    2326            }
    2327        }
    2328
    2329        return null;
    2330    }
    

    当Service所在进程没启动时,会首先启动进程,将Service放入pendingServices中,等到进程正式启动在attachApplicationLocked中正式将待启动的Service通过
    realStartServiceLocked启动

    ActiveServices#attachApplicationLocked

    在其中启动pendingService和restartService

    2967    boolean attachApplicationLocked(ProcessRecord proc, String processName)
    2968            throws RemoteException {
    2969        boolean didSomething = false;
    2970        // Collect any services that are waiting for this process to come up.
    2971        if (mPendingServices.size() > 0) {
    2972            ServiceRecord sr = null;
    2973            try {
    2974                for (int i=0; i<mPendingServices.size(); i++) {
    2975                    sr = mPendingServices.get(i);
    2976                    if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
    2977                            || !processName.equals(sr.processName))) {
    2978                        continue;
    2979                    }
    2980
    2981                    mPendingServices.remove(i);
    2982                    i--;
    2983                    proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
    2984                            mAm.mProcessStats);
    2985                    realStartServiceLocked(sr, proc, sr.createdFromFg);
    2986                    didSomething = true;
    2987                    if (!isServiceNeededLocked(sr, false, false)) {
    2988                        // We were waiting for this service to start, but it is actually no
    2989                        // longer needed.  This could happen because bringDownServiceIfNeeded
    2990                        // won't bring down a service that is pending...  so now the pending
    2991                        // is done, so let's drop it.
    2992                        bringDownServiceLocked(sr);
    2993                    }
    2994                }
    2995            } catch (RemoteException e) {
    2996                Slog.w(TAG, "Exception in new application when starting service "
    2997                        + sr.shortName, e);
    2998                throw e;
    2999            }
    3000        }
    3001        // Also, if there are any services that are waiting to restart and
    3002        // would run in this process, now is a good time to start them.  It would
    3003        // be weird to bring up the process but arbitrarily not let the services
    3004        // run at this point just because their restart time hasn't come up.
    3005        if (mRestartingServices.size() > 0) {
    3006            ServiceRecord sr;
    3007            for (int i=0; i<mRestartingServices.size(); i++) {
    3008                sr = mRestartingServices.get(i);
    3009                if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
    3010                        || !processName.equals(sr.processName))) {
    3011                    continue;
    3012                }
    3013                mAm.mHandler.removeCallbacks(sr.restarter);
    3014                mAm.mHandler.post(sr.restarter);
    3015            }
    3016        }
    3017        return didSomething;
    3018    }
    

    真正启动服务的操作realStartServiceLocked对于unbind Service1. 修改ServiceRecord状态 2.调用create相关函数,创建Service 3.发送参数
    ActiveServices#realStartServiceLocked

    2342    private final void realStartServiceLocked(ServiceRecord r,
    2343            ProcessRecord app, boolean execInFg) throws RemoteException {
    2344        if (app.thread == null) {
    2345            throw new RemoteException();
    2346        }
    2347        if (DEBUG_MU)
    2348            Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
    2349                    + ", ProcessRecord.uid = " + app.uid);
    2350        r.app = app;
    2351        r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
    2352
    2353        final boolean newService = app.services.add(r);
    2354        bumpServiceExecutingLocked(r, execInFg, "create"); //对服务状态进行记录,第二个参数代表是否是前台服务,最后一个参数代表reason
    2355        mAm.updateLruProcessLocked(app, false, null);
    2356        updateServiceForegroundLocked(r.app, /* oomAdj= */ false); //更新服务所在进程的优先级
    2357        mAm.updateOomAdjLocked();
    2358
    2359        boolean created = false;
    2360        try {
    2361            if (LOG_SERVICE_START_STOP) {
    2362                String nameTerm;
    2363                int lastPeriod = r.shortName.lastIndexOf('.');
    2364                nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
    2365                EventLogTags.writeAmCreateService(
    2366                        r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
    2367            }
    2368            synchronized (r.stats.getBatteryStats()) {
    2369                r.stats.startLaunchedLocked();
    2370            }
    2371            mAm.notifyPackageUse(r.serviceInfo.packageName,
    2372                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
    2373            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); //更新进程状态为PROCESS_STATE_SERVICE
    2374            app.thread.scheduleCreateService(r, r.serviceInfo,
    2375                    mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
    2376                    app.repProcState); //通过binder通信,直接调用客户端所在进程的ActivityThread,进行创建服务的工作
    2377            r.postNotification();  //应该是针对前台服务post notification
    2378            created = true;
    2379        } catch (DeadObjectException e) { //如果startService时,Service所在进程正好被杀了,这是没有办法进行通信的,binderdied
    2380            Slog.w(TAG, "Application dead when creating service " + r);
    2386            mAm.appDiedLocked(app); //调用appDiedLocked来将被kill的进程杀死,完全清理
    2387            throw e; //并且抛出异常
    2388        } finally {
    2389            if (!created) {//服务创建失败
    2390                // Keep the executeNesting count accurate.
    2391                final boolean inDestroying = mDestroyingServices.contains(r);
    2392                serviceDoneExecutingLocked(r, inDestroying, inDestroying); //更新ServiceRecord相关的统计信息
    2393
    2394                // Cleanup.
    2395                if (newService) {
    2396                    app.services.remove(r); //清理所在进程中的services统计
    2397                    r.app = null;
    2398                    if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
    2399                    Slog.w(TAG, " Failed to create Service !!!! ."
    2400                           +"This will introduce huge delay...  "
    2401                           +r.shortName + " in " + r.restartDelay + "ms");
    2402                    }
    2403                }
    2404
    2405                // Retry.
    2406                if (!inDestroying) {
    2407                    scheduleServiceRestartLocked(r, false); //如果要启动的Service不在destroy队列中,且没启动成功,安排重新启动Service(在里面高通做了优化导致的问题,导致一直delay)
    2408                }
    2409            }
    2410        }
    2411
    2412        if (r.whitelistManager) {
    2413            app.whitelistManager = true;
    2414        }
    2415  
    2416        requestServiceBindingsLocked(r, execInFg); //与bindService有关,调用Service的onBind函数 //Service被绑定过,才会调用onBind函数
    2417
    2418        updateServiceClientActivitiesLocked(app, null, true);  //如果客户端Bind Service成功,按需更新服务端进程优先级
    2419
    2420        // If the service is in the started state, and there are no
    2421        // pending arguments, then fake up one so its onStartCommand() will
    2422        // be called.
    2423        if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
    2424            r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
    2425                    null, null, 0));
    2426        }
    2427
    2428        sendServiceArgsLocked(r, execInFg, true);//果然会调用到sendServiceArgsLocked发送参数
    2429
    2430        if (r.delayed) { //如果Service是延迟启动的,那么此时可以将其从mDelayedStartList移除(针对延迟启动Service的情况)
    2431            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
    2432            getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
    2433            r.delayed = false;
    2434        }
    2435
    2436        if (r.delayedStop) {//若Service被要求停止,那么结束服务
    2437            // Oh and hey we've already been asked to stop!
    2438            r.delayedStop = false;
    2439            if (r.startRequested) {
    2440                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    2441                        "Applying delayed stop (from start): " + r);
    2442                stopServiceLocked(r);
    2443            }
    2444        }
    2445    }
    

    从代码来看,对于Unbounded Service而言,realStartServiceLocked函数最主要的工作是:
    1、利用bumpServiceExecutingLocked函数,记录ServiceRecord的执行状态;
    2、利用scheduleCreateService函数,创建出Service对象;
    3、如果创建失败,视情况重启Service,调用scheduleServiceRestartLocked
    4、利用sendServiceArgsLocked函数,将Intent中的信息递交给Service处理。
    ActiveServices#scheduleServiceRestartLocked
    首先看不正常的逻辑scheduleServiceRestartLocked

    1945    private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
    1952        boolean canceled = false;
    1953        if (mAm.isShuttingDownLocked()) {
    1954            Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
    1955                    + " - system is shutting down");
    1956            return false;
    1957        }
    1958
    1959        ServiceMap smap = getServiceMapLocked(r.userId);
    1960        if (smap.mServicesByName.get(r.name) != r) { //要重启的ServiceRecord不匹配的情况
    1961            ServiceRecord cur = smap.mServicesByName.get(r.name);
    1962            Slog.wtf(TAG, "Attempting to schedule restart of " + r
    1963                    + " when found in map: " + cur);
    1964            return false;
    1965        }
    1966
    1967        final long now = SystemClock.uptimeMillis();
    1968
    1970        //if ((r.serviceInfo.applicationInfo.flags
    1971        //        &ApplicationInfo.FLAG_PERSISTENT) == 0) {
    1972        if ((r.serviceInfo.applicationInfo.flags
    1973                &ApplicationInfo.FLAG_PERSISTENT) == 0
    1974                && !ActiveServicesInjector.willRestartNow(r)) {
    1975            long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
    1976            long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
    1977        // END
    1978
    1979            // Any delivered but not yet finished starts should be put back
    1980            // on the pending list.
    1981            final int N = r.deliveredStarts.size(); //重启服务时所有还没有被处理完的startItem请求被放入pendinglist(pendingStarts)
    1982            if (N > 0) {
    1983                for (int i=N-1; i>=0; i--) {
    1984                    ServiceRecord.StartItem si = r.deliveredStarts.get(i);
    1985                    si.removeUriPermissionsLocked();
    1986                    if (si.intent == null) {
    1987                        // We'll generate this again if needed.
    1988                    } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
    1989                            && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
    1990                        r.pendingStarts.add(0, si);//添加到pendingStarts
    1991                        long dur = SystemClock.uptimeMillis() - si.deliveredTime;
    1992                        dur *= 2;
    1993                        if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
    1994                            Slog.w(TAG,"Can add more delay !!!"
    1995                               +" si.deliveredTime "+si.deliveredTime
    1996                               +" dur "+dur
    1997                               +" si.deliveryCount "+si.deliveryCount
    1998                               +" si.doneExecutingCount "+si.doneExecutingCount
    1999                               +" allowCancel "+allowCancel);
    2000                        }
    2001                        if (minDuration < dur) minDuration = dur;
    2002                        if (resetTime < dur) resetTime = dur;
    2003                    } else {
    2004                        Slog.w(TAG, "Canceling start item " + si.intent + " in service "
    2005                                + r.name);
    2006                        canceled = true;
    2007                    }
    2008                }
    2009                r.deliveredStarts.clear();
    2010            }
    2011                                       
    2012            r.totalRestartCount++; 
                       //计算delay时间
    2013            if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
    2014                Slog.w(TAG,"r.name "+r.name+" N "+N+" minDuration "+minDuration
    2015                       +" resetTime "+resetTime+" now "+now
    2016                       +" r.restartDelay "+r.restartDelay
    2017                       +" r.restartTime+resetTime "+(r.restartTime+resetTime)
    2018                       +" allowCancel "+allowCancel);
    2019            }
    2020            if (r.restartDelay == 0) {
    2021                r.restartCount++;
    2022                r.restartDelay = minDuration; //delay until next restart attempt. 
    2023            } else if (r.crashCount > 1) {
    2024                r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
    2025                        * (r.crashCount - 1);
    2026            } else {
    2027                // If it has been a "reasonably long time" since the service
    2028                // was started, then reset our restart duration back to
    2029                // the beginning, so we don't infinitely increase the duration
    2030                // on a service that just occasionally gets killed (which is
    2031                // a normal case, due to process being killed to reclaim memory).
    2032                if (now > (r.restartTime+resetTime)) {
    2033                    r.restartCount = 1;
    2034                    r.restartDelay = minDuration;
    2035                } else {
    2036                    r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
    2037                    if (r.restartDelay < minDuration) {
    2038                        r.restartDelay = minDuration;
    2039                    }
    2040                }
    2041            }
    2042
    2043            r.nextRestartTime = now + r.restartDelay; 
    2044            if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
    2045                Slog.w(TAG,"r.name "+r.name+" N "+N+" minDuration "+minDuration
    2046                       +" resetTime "+resetTime+" now "+now
    2047                       +" r.restartDelay "+r.restartDelay
    2048                       +" r.restartTime+resetTime "+(r.restartTime+resetTime)
    2049                       +" r.nextRestartTime "+r.nextRestartTime
    2050                       +" allowCancel "+allowCancel);
    2051            }
    2052
    2053            // Make sure that we don't end up restarting a bunch of services
    2054            // all at the same time.
    2055            boolean repeat;
    2056            do {
    2057                repeat = false;
    2058                final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
    2059                for (int i=mRestartingServices.size()-1; i>=0; i--) {
    2060                    ServiceRecord r2 = mRestartingServices.get(i);
    2061                    if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
    2062                            && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
    2063                        r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
    2064                        r.restartDelay = r.nextRestartTime - now;
    2065                        repeat = true;
    2066                        break;
    2067                    }
    2068                }
    2069            } while (repeat);
    2070
    2071        } else {
    2072            // Persistent processes are immediately restarted, so there is no
    2073            // reason to hold of on restarting their services.
    2074            r.totalRestartCount++;
    2075            r.restartCount = 0;
    2076            r.restartDelay = 0;
    2077            r.nextRestartTime = now;
    2078        } 
    /*
    114    long restartDelay;      // delay until next restart attempt.
    115    long restartTime;       // time of last restart.
    116    long nextRestartTime;   // time when restartDelay will expire.  //上面的作用都是计算下次restart的时间
    */
    2079
    2080        if (!mRestartingServices.contains(r)) {
    2081            r.createdFromFg = false;
    2082            mRestartingServices.add(r);//添加到 mRestartingServices队列
    2083            r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
    2084        }
    2085
    2086        cancelForegroundNotificationLocked(r);
    2087
    2088        mAm.mHandler.removeCallbacks(r.restarter);
    2089        mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime); //通过一个线程来定时restart Service 应该是ServiceRestarter(在未来的固定时间来触发restart该Service)
    2090        r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
    2091        Slog.w(TAG, "Scheduling restart of crashed service "
    2092                + r.shortName + " in " + r.restartDelay + "ms");
    2093
    2094        if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
    2095            for (int i=mRestartingServices.size()-1; i>=0; i--) {
    2096                ServiceRecord r2 = mRestartingServices.get(i);
    2097                Slog.w(TAG,"Restarting list - i "+i+" r2.nextRestartTime "
    2098                           +r2.nextRestartTime+" r2.name "+r2.name);
    2099            }
    2100        }
    2101
    2102        EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
    2103                r.userId, r.shortName, r.restartDelay);
    2104
    2105        return canceled;
    2106    }
    
    1703    private class ServiceRestarter implements Runnable {
    1704        private ServiceRecord mService;
    1705
    1706        void setService(ServiceRecord service) {
    1707            mService = service;
    1708        }
    1709
    1710        public void run() {
    1711            synchronized(mAm) {
    1712                performServiceRestartLocked(mService);
    1713            }
    1714        }
    1715    }
    
    //aosp:
        final void performServiceRestartLocked(ServiceRecord r) {
            if (!mRestartingServices.contains(r)) {
                return;
            }
            if (!isServiceNeededLocked(r, false, false)) {
                // Paranoia: is this service actually needed?  In theory a service that is not
                // needed should never remain on the restart list.  In practice...  well, there
                // have been bugs where this happens, and bad things happen because the process
                // ends up just being cached, so quickly killed, then restarted again and again.
                // Let's not let that happen.
                Slog.wtf(TAG, "Restarting service that is not needed: " + r);
                return;
            }
            try {
                bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
            } catch (TransactionTooLargeException e) {
                // Ignore, it's been logged and nothing upstack cares.
            }
        }
    
    //aosp+高通优化:
    2108    final void performServiceRestartLocked(ServiceRecord r) {
    2109        if (!mRestartingServices.contains(r)) {
    2110            return;
    2111        }
    2112        if (!isServiceNeededLocked(r, false, false)) {
    2113            // Paranoia: is this service actually needed?  In theory a service that is not
    2114            // needed should never remain on the restart list.  In practice...  well, there
    2115            // have been bugs where this happens, and bad things happen because the process
    2116            // ends up just being cached, so quickly killed, then restarted again and again.
    2117            // Let's not let that happen.
    2118            Slog.wtf(TAG, "Restarting service that is not needed: " + r);
    2119            return;
    2120        }
    2121        try {
    2122            if(SERVICE_RESCHEDULE) { //在这里可能会陷入循环delay
    2123                boolean shouldDelay = false;
    2124                ActivityRecord top_rc = null;
    2125                ActivityStack stack = mAm.getFocusedStack();
    2126                if(stack != null) {
    2127                    top_rc = stack.topRunningActivityLocked();
    2128                }
    2129
    2130                boolean isPersistent
    2131                        = !((r.serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0);
    2132                if(top_rc != null) {
    2133                    if(top_rc.launching && !r.shortName.contains(top_rc.packageName)
    2134                            && !isPersistent) { //ActivityRecord launching boolean launching;      // is activity launch in progress?
    2135                        shouldDelay = true;
    2136                    }
    2137                }
    2138                if(!shouldDelay) {
    2139                    bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
    2140                } else {
    2141                    if (DEBUG_DELAYED_SERVICE) {
    2142                        Slog.v(TAG, "Reschedule service restart due to app launch"
    2143                              +" r.shortName "+r.shortName+" r.app = "+r.app);
    2144                    }
    2145                    r.resetRestartCounter();
    2146                    scheduleServiceRestartLocked(r, true);
    2147                }
    2148            } else {
    2149                bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
    2150            }
    2151        } catch (TransactionTooLargeException e) {
    2152            // Ignore, it's been logged and nothing upstack cares.
    2153        }
    2154    }
    

    unbouned service start时序图

    Unbounded start Service uml.png

    参考: Android 7.0 ActivityManagerService(6) Service相关流程分析

    相关文章

      网友评论

        本文标题:Service相关流程学习-Unbouned Start Ser

        本文链接:https://www.haomeiwen.com/subject/xgvpqqtx.html