操作系统的引导文件去运行linux的内核程序,内核程序开始启动的时候会加载各种驱动和数据结构,开始加载android应用层的第一个进程(init进程c代码(system\core\init目录)
下面就从开始加载android第一个进程说起,注意代码中的注释,另附图一张以便理解
int main(int argc, char **argv)
{
...
创建目录并且挂载该目录
//初始化日志
log_init();
...
//解析配置文件
init_parse_config_file("/init.rc");
...
return 0;
}
...
//孵化器进程,它是很多其他应用进程的母进程
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
socket zygote stream 666
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
...
int main(int argc, const char* const argv[])
{
...
if (i < argc) {
arg = argv[i++];
if (0 == strcmp("--zygote", arg)) {
bool startSystemServer = (i < argc) ?
strcmp(argv[i], "--start-system-server") == 0 : false;
setArgv0(argv0, "zygote");
set_process_name("zygote");
runtime.start("com.android.internal.os.ZygoteInit",
startSystemServer);
}
...
}
public static void main(String argv[]) {
try {
//设置最小堆内存5M
VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024);
。。。
//预加载类和资源 ,该方法细节看2步
preloadClasses();
//强制执行一次垃圾收集
// Do an initial gc to clean up after startup
gc();
// 传入的参数满足if 等于true,不然抛异常
if (argv[1].equals("true")) {
startSystemServer();//详情看第3步
}
。。。
}//end main
//2步 preloadClasses()
private static void preloadClasses() {
final VMRuntime runtime = VMRuntime.getRuntime();
InputStream is = ZygoteInit.class.getClassLoader().getResourceAsStream(
PRELOADED_CLASSES);//类的配置文件 1800多个类
try {
BufferedReader br
= new BufferedReader(new InputStreamReader(is), 256);
int count = 0;
String line;
while ((line = br.readLine()) != null) {
Class.forName(line);//加载每一个类
。。。
}
//3步 startSystemServer()方法
private static boolean startSystemServer()
throws MethodAndArgsCaller, RuntimeException {
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",
"--capabilities=130104352,130104352",
"--runtime-init",
"--nice-name=system_server",//进程的名字system_server
"com.android.server.SystemServer",//启动的类名
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
//把参数封装到对象中
parsedArgs = new ZygoteConnection.Arguments(args);
//分叉进程
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
。。。
return true;
}
public static void main(String[] args) {
。。。。
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
//加载android_servers库 jni
System.loadLibrary("android_servers"); //加载 libxxx.so文件
init1(args);//通过jni调用的目的:通过c来启动底层的硬件服务
}
native public static void init1(String[] args); //在c或c++中实现
//这里写代码片System_init.cpp中,详情看2步
extern "C" int system_init();
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{ //调用此方法!!!!
system_init();
}
/*
* JNI registration.
*/
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};
//2步 System_init.cpp类 中system_init()方法主要代码如下:
extern "C" status_t system_init()
{
LOGI("Entered system_init()");
// Start the sensor service
SensorService::instantiate();
// 启动硬件服务(c代码才可以直接操作硬件)
if (!proc->supportsProcesses()) {
// Start the AudioFlinger
AudioFlinger::instantiate();
// Start the media playback service
MediaPlayerService::instantiate();
// Start the camera service
CameraService::instantiate();
// Start the audio policy service
AudioPolicyService::instantiate();
}
LOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
//详情看3步
runtime->callStatic("com/android/server/SystemServer", "init2");
...
return NO_ERROR;
//3步 SystemServer类的静态方法init2,主要代码如下:
Slog.i(TAG, "Entered the Android system server!");
//启动线程
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
@Override
public void run() {
//轮询器的初始化
Looper.prepare();
。。。
//启动各种服务
// make sure the ADB_ENABLED setting value matches the secure
//几种服务的ready准备
。。。
((ActivityManagerService)ActivityManagerNative.getDefault())
.systemReady(new Runnable() {
public void run() {
Slog.i(TAG, "Making services ready");
if (statusBarF != null) statusBarF.systemReady2();
if (batteryF != null) batteryF.systemReady();
if (connectivityF != null) connectivityF.systemReady();
if (dockF != null) dockF.systemReady();
if (usbF != null) usbF.systemReady();
if (uiModeF != null) uiModeF.systemReady();
if (recognitionF != null) recognitionF.systemReady();
Watchdog.getInstance().start();
// It is now okay to let the various system services start their
// third party code...
if (appWidgetF != null) appWidgetF.systemReady(safeMode);
if (wallpaperF != null) wallpaperF.systemReady();
if (immF != null) immF.systemReady();
if (locationF != null) locationF.systemReady();
if (throttleF != null) throttleF.systemReady();
}
});
。。。
//轮询器已经开监听消息(轮询取消息)
Looper.loop();
Slog.d(TAG, "System ServerThread is exiting!");
}
public void systemReady(final Runnable goingCallback) {
r
。。。。
final ArrayList doneReceivers = new ArrayList();
。。。
加载各种Activity组件
//任务栈
mMainStack.resumeTopActivityLocked(null);
}
}
final boolean resumeTopActivityLocked(ActivityRecord prev) {
//系统刚开始启动,任务栈中还不存在Activity
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
//第一次加载,没有任何Activity存在
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
//系统刚开始启动成功 ,返回的就是待机画面的Activity
return mService.startHomeActivityLocked();
}
}
...
}
上图: