persistent應(yīng)用的啟動(dòng)過程以及重啟機(jī)制

之前確實(shí)沒使用過這個(gè)屬性,前幾天在查找“怎么保證Service不被Kill”這個(gè)問題的答案時(shí),我看到有一條是“設(shè)置application的屬性persistent為true”,由于不清楚它的作用和實(shí)現(xiàn)原理,于是有了這篇筆記。

在AndroidManifest.xml定義中,application有這么一個(gè)屬性android:persistent,根據(jù)字面意思來理解就是說該應(yīng)用是可持久的,也即是常駐的應(yīng)用。其實(shí)就是這么個(gè)理解,被android:persistent修飾的應(yīng)用會(huì)在系統(tǒng)啟動(dòng)之后被AMS啟動(dòng)。

在系統(tǒng)啟動(dòng)時(shí),ActivityManagerService會(huì)調(diào)用systemReady()方法來加載所有persistent屬性為true的應(yīng)用。

public void systemReady(final Runnable goingCallback) {
    
    ......

    synchronized (this) {
        // Only start up encryption-aware persistent apps; once user is
        // unlocked we'll come back around and start unaware apps
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);

        ......
    }
}

private void startPersistentApps(int matchFlags) {
    if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;

    synchronized (this) {
        try {
            final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
                    .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
            for (ApplicationInfo app : apps) {
                if (!"android".equals(app.packageName)) {
                    addAppLocked(app, false, null /* ABI override */);
                }
            }
        } catch (RemoteException ex) {
        }
    }
}

上面的代碼中persistent應(yīng)用列表是通過PackageManagerService類的getPersistentApplications()方法來獲取的,方法實(shí)現(xiàn)如下:

@Override
public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
    return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
}

private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
    final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();

    // reader
    synchronized (mPackages) {
        final Iterator<PackageParser.Package> i = mPackages.values().iterator();
        final int userId = UserHandle.getCallingUserId();
        while (i.hasNext()) {
            final PackageParser.Package p = i.next();
            if (p.applicationInfo == null) continue;

            final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
                    && !p.applicationInfo.isDirectBootAware();
            final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
                    && p.applicationInfo.isDirectBootAware();

            if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
                    && (!mSafeMode || isSystemApp(p))
                    && (matchesUnaware || matchesAware)) {
                PackageSetting ps = mSettings.mPackages.get(p.packageName);
                if (ps != null) {
                    ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
                            ps.readUserState(userId), userId);
                    if (ai != null) {
                        finalList.add(ai);
                    }
                }
            }
        }
    }

    return finalList;
}

在PackageManagerService中,有一個(gè)記錄所有的程序包信息的哈希表(mPackages),每個(gè)表項(xiàng)中含有ApplicationInfo信息,該信息的flags(int型)數(shù)據(jù)中有一個(gè)專門的bit用于表示persistent。getPersistentApplications()方法會(huì)遍歷這張表,找出所有persistent包,并返回ArrayList<ApplicationInfo>。不過從代碼中我們看到,除了有FLAG_PERSISTENT標(biāo)志的應(yīng)用,處于非安全模式或者是系統(tǒng)應(yīng)用、直接啟動(dòng)的應(yīng)用,滿足這些條件的應(yīng)用才會(huì)被加到persistent列表中。

接著systemReady方法會(huì)遍歷persistent列表中的ApplicationInfo,然后對包名不為“android”的ApplicationInfo執(zhí)行addAppLocked方法,看看addAppLocked的實(shí)現(xiàn):

final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated, String abiOverride) {
    ProcessRecord app;
    if (!isolated) {
        app = getProcessRecordLocked(info.processName, info.uid, true);
    } else {
        app = null;
    }

    if (app == null) {
        app = newProcessRecordLocked(info, null, isolated, 0);
        updateLruProcessLocked(app, false, null);
        updateOomAdjLocked();
    }

    // This package really, really can not be stopped.
    try {
        AppGlobals.getPackageManager().setPackageStoppedState(
                info.packageName, false, UserHandle.getUserId(app.uid));
    } catch (RemoteException e) {
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Failed trying to unstop package "
                + info.packageName + ": " + e);
    }

    if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
        app.persistent = true;
        app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
    }
    if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
        mPersistentStartingProcesses.add(app);
        startProcessLocked(app, "added application", app.processName, abiOverride,
                null /* entryPoint */, null /* entryPointArgs */);
    }

    return app;
}

這個(gè)方法的作用主要是添加一個(gè)與App進(jìn)程對應(yīng)的ProcessRecord節(jié)點(diǎn),如果這個(gè)節(jié)點(diǎn)已經(jīng)添加過了,那么是不會(huì)重復(fù)添加的。在添加節(jié)點(diǎn)的動(dòng)作完成以后,addAppLocked()還會(huì)檢查App進(jìn)程是否已經(jīng)啟動(dòng)好了,如果尚未開始啟動(dòng),此時(shí)就會(huì)調(diào)用startProcessLocked()來啟動(dòng)這個(gè)進(jìn)程。既然addAppLocked()試圖確認(rèn)App“正在正常運(yùn)作”或者“將被正常啟動(dòng)”,那么其對應(yīng)的package就不可能處于stopped狀態(tài),這就是上面代碼調(diào)用setPackageStoppedState(..., false,...)以及注釋“This package really, really can not be stopped.”的作用。

因?yàn)閱?dòng)過程異步,所以對于正在啟動(dòng)但尚未啟動(dòng)完成的ApplicationInfo,AMS會(huì)把他們添加到一個(gè)緩沖列表中也就是mPersistentStartingProcesses這個(gè)變量中記錄,啟動(dòng)一個(gè)進(jìn)程則是調(diào)用startProcessLocked方法,其中啟動(dòng)代碼如下:

Process.ProcessStartResult startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, debugFlags, mountExternal,
                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
                    app.info.dataDir, entryPointArgs);

一旦啟動(dòng)完成,這個(gè)用戶進(jìn)程會(huì)被attach到系統(tǒng)中,這個(gè)我們看ActivityThread中的main方法就可知:

ActivityThread thread = new ActivityThread();
thread.attach(false);
private void attach(boolean system) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ViewRootImpl.addFirstDrawHandler(new Runnable() {
            @Override
            public void run() {
                ensureJitEnabled();
            }
        });
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        final IActivityManager mgr = ActivityManagerNative.getDefault();
        try {
            mgr.attachApplication(mAppThread);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ......
    } else {
        ......
    }

    ......
}

attach方法中會(huì)判斷不是系統(tǒng)應(yīng)用就會(huì)調(diào)用AMS的attachApplication方法(AMS繼承自ActivityManagerNative),在attach過程中,ActivityThread會(huì)將對應(yīng)的application attach到AM中去,交給AM去管理,在這個(gè)方法中傳遞了一個(gè)變量mAppThread,它是一個(gè)ApplicationThread對象,ApplicationThread是定義在ActivityThread類中的繼承ApplicationThreadNative的私有類,它繼承自Binder且實(shí)現(xiàn)了IApplicationThread接口,所以在AMS中的關(guān)于ApplicationThread的參數(shù)都是IApplicationThread的形式,mAppThread可以看作是當(dāng)前進(jìn)程主線程的核心,它負(fù)責(zé)處理本進(jìn)程與其他進(jìn)程(主要是AM)之間的通信,同時(shí)通過attachApplication將mAppThread的代理Binder傳遞給AM。接著ApplicationInfo走到attachApplicationLocked方法。

@Override
public final void attachApplication(IApplicationThread thread) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid);
        Binder.restoreCallingIdentity(origId);
    }
}
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {

    ......

    // If this application record is still attached to a previous
    // process, clean it up now.
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }

    final String processName = app.processName;
    try {
        // 注冊進(jìn)程死亡監(jiān)聽器
        AppDeathRecipient adr = new AppDeathRecipient(app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0);
        app.deathRecipient = adr;
    } catch (RemoteException e) {
        app.resetPackageList(mProcessStats);
        startProcessLocked(app, "link fail", processName);
        return false;
    }

    ......
  
    thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
            profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
            app.instrumentationUiAutomationConnection, testMode,
            mBinderTransactionTrackingEnabled, enableTrackAllocation,
            isRestrictedBackupMode || !normalMode, app.persistent,
            new Configuration(mConfiguration), app.compat,
            getCommonServicesLocked(app.isolated),
            mCoreSettingsObserver.getCoreSettingsLocked());

    // Remove this record from the list of starting applications.
    mPersistentStartingProcesses.remove(app);

    ......

    return true;
}

在attachApplicationLocked方法中AMS調(diào)用到了IPC通信調(diào)用mAppThread的bindApplication方法,然后將該P(yáng)rocessRecord節(jié)點(diǎn)在mPersistentStartingProcesses列表中移除。
這里又回調(diào)到了ApplicationThread類中的bindApplication方法:

public final void bindApplication(String processName, ApplicationInfo appInfo,
                List<ProviderInfo> providers, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) {

    if (services != null) {
        // Setup the service cache in the ServiceManager
        ServiceManager.initServiceCache(services);
    }

    setCoreSettings(coreSettings);

    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providers;
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
    data.instrumentationWatcher = instrumentationWatcher;
    data.instrumentationUiAutomationConnection = instrumentationUiConnection;
    data.debugMode = debugMode;
    data.enableBinderTracking = enableBinderTracking;
    data.trackAllocation = trackAllocation;
    data.restrictedBackupMode = isRestrictedBackupMode;
    data.persistent = persistent;
    data.config = config;
    data.compatInfo = compatInfo;
    data.initProfilerInfo = profilerInfo;
    sendMessage(H.BIND_APPLICATION, data);
}

上述代碼中通過消息機(jī)制向ActivityThread自身維護(hù)的handler發(fā)送BIND_APPLICATION消息。ActivityThread自身維護(hù)的handler對消息BIND_APPLICATION的處理調(diào)用了handleBindApplication方法,而這個(gè)方法中我們可以看到下面這條代碼:

mInstrumentation.callApplicationOnCreate(app);

這句作用是調(diào)用persistent應(yīng)用的Applicaiton中的onCreate方法。

上面說了persistent應(yīng)用的啟動(dòng)過程,既然是persistent的,那么當(dāng)用應(yīng)用出現(xiàn)異常時(shí)它也需要自動(dòng)重啟。這里Android系統(tǒng)中實(shí)現(xiàn)自動(dòng)重啟的做法是這樣的,我們回頭看看上面attachApplicationLocked方法中在bindApplication之前,會(huì)構(gòu)建一個(gè)AppDeathRecipient,相當(dāng)于一個(gè)監(jiān)聽器,然后把這個(gè)監(jiān)聽器跟persistent進(jìn)程綁在一起,由AMS來監(jiān)聽,當(dāng)persistent進(jìn)程意外死亡時(shí),AMS就能知道,并且會(huì)嘗試重新啟動(dòng)這個(gè)應(yīng)用。

AppDeathRecipient的實(shí)現(xiàn)如下:

private final class AppDeathRecipient implements IBinder.DeathRecipient {
    final ProcessRecord mApp;
    final int mPid;
    final IApplicationThread mAppThread;

    AppDeathRecipient(ProcessRecord app, int pid,
            IApplicationThread thread) {
        if (DEBUG_ALL) Slog.v(
            TAG, "New death recipient " + this
            + " for thread " + thread.asBinder());
        mApp = app;
        mPid = pid;
        mAppThread = thread;
    }

    @Override
    public void binderDied() {
        if (DEBUG_ALL) Slog.v(
            TAG, "Death received in " + this
            + " for thread " + mAppThread.asBinder());
        synchronized(ActivityManagerService.this) {
            appDiedLocked(mApp, mPid, mAppThread, true);
        }
    }
}

當(dāng)persistent應(yīng)用意外退出時(shí),系統(tǒng)會(huì)回調(diào)AppDeathRecipient的binderDied方法,這個(gè)方法中只會(huì)執(zhí)行appDiedLocked這個(gè)方法,而最終會(huì)執(zhí)行handleAppDiedLocked這個(gè)方法:

private final void handleAppDiedLocked(ProcessRecord app,
            boolean restarting, boolean allowRestart) {
    int pid = app.pid;
    boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
            false /*replacingPid*/);
    if (!kept && !restarting) {
        removeLruProcessLocked(app);
        if (pid > 0) {
            ProcessList.remove(pid);
        }
    }

    if (mProfileProc == app) {
        clearProfilerLocked();
    }

    // Remove this application's activities from active lists.
    boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);

    app.activities.clear();

    if (app.instrumentationClass != null) {
        Slog.w(TAG, "Crash of app " + app.processName
              + " running instrumentation " + app.instrumentationClass);
        Bundle info = new Bundle();
        info.putString("shortMsg", "Process crashed.");
        finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
    }

    if (!restarting && hasVisibleActivities
            && !mStackSupervisor.resumeFocusedStackTopActivityLocked()) {
        // If there was nothing to resume, and we are not already restarting this process, but
        // there is a visible activity that is hosted by the process...  then make sure all
        // visible activities are running, taking care of restarting this process.
        mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
}

這個(gè)方法的作用就是將進(jìn)程從ActivityManager中移除,其中的變量kept是根據(jù)方法cleanUpApplicationRecordLocked的結(jié)果,其意義是是否要保留這個(gè)進(jìn)程,我們看看它的實(shí)現(xiàn):

private final boolean cleanUpApplicationRecordLocked(ProcessRecord app,
            boolean restarting, boolean allowRestart, int index, boolean replacingPid) {
    
    ......

    if (!app.persistent || app.isolated) {
        if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
                "Removing non-persistent process during cleanup: " + app);
        if (!replacingPid) {
            removeProcessNameLocked(app.processName, app.uid);
        }
        if (mHeavyWeightProcess == app) {
            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
                    mHeavyWeightProcess.userId, 0));
            mHeavyWeightProcess = null;
        }
    } else if (!app.removed) {
        // This app is persistent, so we need to keep its record around.
        // If it is not already on the pending app list, add it there
        // and start a new process for it.
        if (mPersistentStartingProcesses.indexOf(app) < 0) {
            mPersistentStartingProcesses.add(app);
            restart = true;
        }
    }
    ......

    if (restart && !app.isolated) {
        // We have components that still need to be running in the
        // process, so re-launch it.
        if (index < 0) {
            ProcessList.remove(app.pid);
        }
        addProcessNameLocked(app);
        startProcessLocked(app, "restart", app.processName);
        return true;
    } else if (app.pid > 0 && app.pid != MY_PID) {
        // Goodbye!
        boolean removed;
        synchronized (mPidsSelfLocked) {
            mPidsSelfLocked.remove(app.pid);
            mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
        }
        mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
        if (app.isolated) {
            mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
        }
        app.setPid(0);
    }
    return false;
}

我們看到如果是persistent應(yīng)用且還沒有被移除,AMS會(huì)重新將它添加到mPersistentStartingProcesses這個(gè)啟動(dòng)緩存列表中,并再調(diào)用startProcessLocked方法重啟進(jìn)程。到此,persistent應(yīng)用的重啟機(jī)制也就說完了。

參考文章:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容