Android开发程序员

android N phone进程的启动

2018-02-27  本文已影响18人  代码视觉

首先,开机后当zygote启动后会fork出systemserver

   public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        VM_HOOKS.preFork();
        int pid = nativeForkSystemServer(
                uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
        // Enable tracing as soon as we enter the system_server.
        if (pid == 0) {
            Trace.setTracingEnabled(true);
        }
        VM_HOOKS.postForkCommon();
        return pid;
    }

当systemserver创建之后,在systemserver的run方法中会Start services。其中

startBootstrapServices();
startCoreServices();
startOtherServices();

在startOtherServices();

   mActivityManagerService.systemReady(new Runnable() {
    ......
}

接着在activitymanagerservices的systemRead他中

   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);//启动所有PackageManager.MATCH_DIRECT_BOOT_AWARE标志为true的应用

MATCH_DIRECT_BOOT_AWARE他是定义在 /android/applications/sources/services/Telephony/对应的AndroidManefest.xml文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
            package="com.android.phone"
            android:versionCode="1"
            android:versionName="1.0.0"
            coreApp="true"
            android:sharedUserId="android.uid.phone"
            android:sharedUserLabel="@string/phoneAppLabel" >
            .....
        <application android:name="PhoneApp"
            android:persistent="true"/*这个为true表示为常驻进程*/
            android:hardwareAccelerated="true"
            android:label="@string/phoneAppLabel"
            android:icon="@mipmap/ic_launcher_phone"
            android:allowBackup="false"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
            android:defaultToDeviceProtectedStorage="true"
            android:directBootAware="true">
            ....
        </application>
    </manifest>
 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) {
            }
        }
    }
 //添加应用程序进程到LRU列表中,并创建进程
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);
        }

        /// M: [process suppression] @{
        if ("1".equals(SystemProperties.get("persist.runningbooster.support")) ||
                "1".equals(SystemProperties.get("ro.mtk_aws_support"))) {
            AMEventHookData.PackageStoppedStatusChanged eventData =
                    AMEventHookData.PackageStoppedStatusChanged.createInstance();
            eventData.set(info.packageName, SUPPRESS_ACTION_UNSTOP, "addAppLocked");
            mAMEventHook.hook(AMEventHook.Event.AM_PackageStoppedStatusChanged, eventData);
        }
        /// M: [process suppression] @}

        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;
    }
 private final void startProcessLocked(ProcessRecord app, String hostingType,
                String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {

                Process.ProcessStartResult startResult = null;

                if(userid>0 && (bbcId>0 && userid == bbcId) && app.info.bbcseinfo!=null){
                    //启动进程                
                    startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, debugFlags, mountExternal,
                    app.info.targetSdkVersion, app.info.bbcseinfo, app.info.bbccategory, app.info.accessInfo,
                    requiredAbi, instructionSet,
                    app.info.dataDir, mountKnoxPoint, entryPointArgs);
                }esle{
                    ...
                }
        }

调用Process.start(),创建一个新的进程ActivityThread,Phone进程就运行在该进程当中:

 public static final ProcessStartResult start(final String processClass,
                                  final String niceName,
                                  int uid, int gid, int[] gids,
                                  int debugFlags, int mountExternal,
                                  int targetSdkVersion,
                                  String seInfo,
                                  int category,
                                  int accessInfo,
                                  String abi,
                                  String instructionSet,
                                  String appDataDir,
                                  boolean mountKnoxPoint,
                                  String[] zygoteArgs) {
        try {
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    debugFlags, mountExternal, targetSdkVersion, seInfo, category, accessInfo,
                    abi, instructionSet, appDataDir, mountKnoxPoint, zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
            Log.e(LOG_TAG,
                    "Starting VM process through Zygote failed");
            throw new RuntimeException(
                    "Starting VM process through Zygote failed", ex);
        }
    }```
发送消息到zygote的socket端口,请求创建新的进程:
private static ProcessStartResult startViaZygote(final String processClass,
                                  final String niceName,
                                  final int uid, final int gid,
                                  final int[] gids,
                                  int debugFlags, int mountExternal,
                                  int targetSdkVersion,
                                  String seInfo,
                                  int category,
                                  int accessInfo,
                                  String abi,
                                  String instructionSet,
                                  String appDataDir,
                                  boolean mountKnoxPoint,
                                  String[] extraArgs)
                                  throws ZygoteStartFailedEx {
        synchronized(Process.class) {
            ArrayList<String> argsForZygote = new ArrayList<String>();

            // --runtime-args, --setuid=, --setgid=,
            // and --setgroups= must go first
            argsForZygote.add("--runtime-args");
            argsForZygote.add("--setuid=" + uid);
            argsForZygote.add("--setgid=" + gid);
            ....
            if (appDataDir != null) {
                argsForZygote.add("--app-data-dir=" + appDataDir);
            }
            ....
            argsForZygote.add(processClass);

            if (extraArgs != null) {
                for (String arg : extraArgs) {
                    argsForZygote.add(arg);
                }
            }

            //发送消息到zygote的socket端口,请求创建新的进程
            if (Zygote.isEnhancedZygoteASLREnabled) {
                ....
                return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
                // End of isEnhancedZygoteASLREnabled case
            } else {
                // Original case
                return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
            }
        }
    }

至此phoneApp将会被创建出来,在它的oncreate中会创建出PhoneGlobals

public void onCreate() {
// for plug-in
ExtensionManager.init(this);

    if (UserHandle.myUserId() == 0) {
        // We are running as the primary user, so should bring up the
        // global phone state.
        mPhoneGlobals = new PhoneGlobals(this);
        mPhoneGlobals.onCreate();

        mTelephonyGlobals = new TelephonyGlobals(this);
        mTelephonyGlobals.onCreate();
    }
}```

接着在PhoneGlobals中如果callmanager为空的话将会创建出对应的callamnager和PhoneFactory以及NotificationMgr等等。

 if (mCM == null) {
            // Initialize the telephony framework
            PhoneFactory.makeDefaultPhones(this);

            // Start TelephonyDebugService After the default phone is created.
            Intent intent = new Intent(this, TelephonyDebugService.class);
            startService(intent);

            mCM = CallManager.getInstance();
            for (Phone phone : PhoneFactory.getPhones()) {
                mCM.registerPhone(phone);
            }

此后将进入到Phonefactory中,在makeDefaultPhones中调用makeDefaultPhone,在这个方法中将进行SubscriptionController,RadioManager,UiccController,phone,SubscriptionInfoUpdater等等的init操作。

上一篇下一篇

猜你喜欢

热点阅读