Android的启动过程,其实就是linux启动过程(Android4.0.2)
init.c
(源码位置:/system/core/init/init.c)
这是一个c文件,系统启动后首先就执行这个文件的main方法
核心源代码:
int main(int argc, char **argv)
{
.
.(初始化操作)
.
/* Get the basic filesystem setup we need put
* together in the initramdisk on / and then we'll
* let the rc file figure out the rest.
*/
mkdir("/dev", 0755);//设备文件
mkdir("/proc", 0755);//进程文件
mkdir("/sys", 0755);
mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
mkdir("/dev/pts", 0755);
mkdir("/dev/socket", 0755);
mount("devpts", "/dev/pts", "devpts", 0, NULL);
mount("proc", "/proc", "proc", 0, NULL);
mount("sysfs", "/sys", "sysfs", 0, NULL);
.
.(初始化操作)
.
INFO("reading config file\n");
init_parse_config_file("/init.rc");//初始化解析配置文件
.
.(初始化操作)
.
return 0;
}
init_parse_config_file("/init.rc");//初始化解析配置文件
init.rc
(源码位置:/system/core/rootdir/init.rc)
这是一个脚本文件,其实就是linux下的脚本文件,一个批处理的脚本
Android在启动过程中读取的启动脚本文件,主要完成一些初级的初始化
rc 经常被用作程序之启动脚本的文件名,它是“run commands”(运行命令)的缩写。
核心源代码:
# setup the global environment(配置环境变量)
export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin
export LD_LIBRARY_PATH /vendor/lib:/system/lib
export ANDROID_BOOTLOGO 1
export ANDROID_ROOT /system
export ANDROID_ASSETS /system/app
export ANDROID_DATA /data
export ANDROID_STORAGE /storage
export ASEC_MOUNTPOINT /mnt/asec
export LOOP_MOUNTPOINT /mnt/obb
export BOOTCLASSPATH /system/framework/core.jar
:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar
:/system/framework/ext.jar:/system/framework/framework.jar
:/system/framework/telephony-common.jar:/system/framework/voip-common.jar
:/system/framework/mms-common.jar:/system/framework/android.policy.jar
:/system/framework/services.jar:/system/framework/apache-xml.jar
.
.(系统文件初始化)
.创建各种目录、加载各种目录
.开启各种服务
.
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
.
.
service zygote /system/bin/app_process//批处理命令:app_process
开启了一个孵化器服务,这是一个脚本的可执行命令
zygote:孵化器,把所有东西都孵化出来了
Android系统 和 Linux内核的结合部分,通过它把整个Android系统启动起来了
App_main.cpp
(源码位置:/frameworks/base/cmds/app_process/app_main.cpp)
这是一个c++文件,执行从main()方法开始
核心源代码:
int main(int argc, const char* const argv[])
{
.
.
AppRuntime runtime;
.
.
// Parse runtime arguments. Stop at first unrecognized option.
bool zygote = false;
.
.
if (zygote) {
runtime.start("com.android.internal.os.ZygoteInit",startSystemServer ? "start-system-server" : "");
} else if (className) {
.
.
} else {
.
.
}
}
这里调用了一个java的类,com.android.internal.os.ZygoteInit
ZygoteInit.java
(源码位置:/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java)
如果java的类直接被调用,也是从main()方法开始执行
终于从C跳转到了java,直接把2进制文件字节码跑起来了
核心源代码:
public static void main(String argv[]) {
try {
...
preload();//加载类和系统资源
...
if (argv[1].equals("start-system-server")) {
startSystemServer();//开启服务
} else if (!argv[1].equals("")) {
...
}
...
} catch (MethodAndArgsCaller caller) {
...
} catch (RuntimeException ex) {
...
}
}
1.proload();加载所有的资源类和系统文件
方法代码:
/**
* The name of a resource file that contains classes to preload.
*/
private static final String PRELOADED_CLASSES = "preloaded-classes";
static void preload() {
//加载所有类
preloadClasses();
//加载所有系统资源,图片文字等
preloadResources();
}
/**
* Performs Zygote process initialization. Loads and initializes
* commonly used classes.
*
* Most classes only cause a few hundred bytes to be allocated, but
* a few will allocate a dozen Kbytes (in one case, 500+K).
*/
private static void preloadClasses() {
final VMRuntime runtime = VMRuntime.getRuntime();
//类加载器,可以从当前包的根目录加载一个资源出来
InputStream is = ZygoteInit.class.getClassLoader().getResourceAsStream(PRELOADED_CLASSES);
if (is == null) {
Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
} else {
...
try {
//把这些类读取出来,然后封装整buffer
BufferedReader br = new BufferedReader(new InputStreamReader(is), 256);
//一行一行的读,每一行就是一个类,然后把类加载进来
int count = 0;
String line;
while ((line = br.readLine()) != null) {
// Skip comments and blank lines.
line = line.trim();
if (line.startsWith("#") || line.equals("")) {
continue;
}
try {
if (false) {
Log.v(TAG, "Preloading " + line + "...");
}
//这样就预加载了系统相关的类,系统基础框架的类就全部加载起来了
Class.forName(line);
if (Debug.getGlobalAllocSize() > PRELOAD_GC_THRESHOLD) {
...
}
count++;
} catch (ClassNotFoundException e) {
...
} catch (Throwable t) {
...
}
}
...
} catch (IOException e) {
...
} finally {
...
}
}
}
/**
* Load in commonly used resources, so they can be shared across
* processes.
*
* These tend to be a few Kbytes, but are frequently in the 20-40K
* range, and occasionally even larger.
*/
private static void preloadResources() {
}
preloaded-classes文件源码:包含所有Android的包名、系统里的所有jar包
# Classes which are preloaded by com.android.internal.os.ZygoteInit.
# Automatically generated by frameworks/base/tools/preload/WritePreloadedClassFile.java.
# MIN_LOAD_TIME_MICROS=1250
# MIN_PROCESSES=10
android.R$styleable
android.accounts.Account
.
android.animation.Animator
.
android.app.ActionBar
.
android.app.Activity
android.app.ActivityManager
.
android.app.ActivityThread
.
android.app.Dialog
.
android.view.View
.
org.apache.http.client.HttpClient
.
2.startSystemServer();开启系统服务。
方法代码:
/**
* Prepare the arguments and fork for the system server process.
*/
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,3006,3007",
"--capabilities=130104352,130104352",
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",//系统服务(android包名)
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
//封装成一个对象(解析成一个对象)
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
//分叉系统服务(就是开启系统服务)
//全部调出去用了,通过孵化器
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
handleSystemServerProcess(parsedArgs);
}
return true;
}
这里是开启系统服务,"com.android.server.SystemServer"
SystemServer.java(系统服务)
(源码位置:/frameworks/base/services/java/com/android/server/SystemServer.java)
从main方法开始执行
核心源代码:
public static void main(String[] args) {
...
...
//jni类库。加载一个c的类库
System.loadLibrary("android_servers");
//jni调用android_servers,c库的方法
init1(args);
}
/**
* This method is called from Zygote to initialize the system. This will cause the native
* services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
* up into init2() to start the Android services.
*/
native public static void init1(String[] args);
初始化一个c库,并调用了c库的方法
android_servers(指向com_android_server_SystemServer.cpp)
(源码位置:/frameworks/base/services/jni/com_android_server_SystemServer.cpp):
这是一个c++文件
核心源代码:
extern "C" int system_init();//这里指向一个c++的文件
//调用的此方法,此方法又调用了上面的方法
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
system_init();方法指向另一个c++的文件
System_init.cpp
(源码位置:/frameworks/base/cmds/system_server/library/system_init.cpp)
核心源代码:
extern "C" status_t system_init()
{
...
...
//初始化硬件管理服务(音频、视频、照相机等)
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the SurfaceFlinger
//触摸屏服务初始化
SurfaceFlinger::instantiate();
}
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the sensor service
//传感器服务初始化
SensorService::instantiate();
}
// And now start the Android runtime. We have to do this bit
// of nastiness because the Android runtime initialization requires
// some of the core system services to already be started.
// All other servers should just start the Android runtime at
// the beginning of their processes's main(), before calling
// the init function.
LOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
LOGI("System server: starting Android services.\n");
JNIEnv* env = runtime->getJNIEnv();
if (env == NULL) {
return UNKNOWN_ERROR;
}
jclass clazz = env->FindClass("com/android/server/SystemServer");
if (clazz == NULL) {
return UNKNOWN_ERROR;
}
jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
if (methodId == NULL) {
return UNKNOWN_ERROR;
}
//通过AndroidRuntime,又回到了SystemServer.jave,的init2()方法
env->CallStaticVoidMethod(clazz, methodId);
...
...
return NO_ERROR;
}
开启所有的硬件服务后又调用了SystemServer.java,init2()方法
SystemServer.java_init2()
核心源代码:
public static final void init2() {
//开启一个线程服务,这个服务是内部类
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
class ServerThread extends Thread {
private static final String TAG = "SystemServer";
private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
private static final String ENCRYPTED_STATE = "1";
ContentResolver mContentResolver;
void reportWtf(String msg, Throwable e) {
Slog.w(TAG, "***********************************************");
Log.wtf(TAG, "BOOT FAILURE " + msg, e);
}
@Override
public void run() {
.
.
//开启器所有系统服务
//先进c打开硬件管理,然后回到java服务,把所有系统服务全部做了初始化
LightsService lights = null;//光线管理
PowerManagerService power = null;//电量管理
BatteryService battery = null;
AlarmManagerService alarm = null;
NetworkManagementService networkManagement = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
WifiP2pService wifiP2p = null;
WifiService wifi = null;
IPackageManager pm = null;
Context context = null;
WindowManagerService wm = null;
BluetoothService bluetooth = null;
BluetoothA2dpService bluetoothA2dp = null;
DockObserver dock = null;
UsbService usb = null;
UiModeManagerService uiMode = null;
RecognitionManagerService recognition = null;
ThrottleService throttle = null;
NetworkTimeUpdateService networkTimeUpdater = null;
.
.
各种服务往里扔,开启
.
.
//系统服务已经处理完成,可以开始处理第三方的部分了
// We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
ActivityManagerService.self().systemReady(new Runnable() {
public void run() {
.
.
.
}
});
}
}
在这里开启所有的软件服务
ActivityManagerService.self().systemReady();//系统服务已经处理完成,可以开始处理第三方的部分了
ActivityManagerService.java
(源码位置:/frameworks/base/services/java/com/android/server/am)
核心源代码:
public void systemReady(final Runnable goingCallback) {
synchronized(this) {
.
.
.
//恢复顶部的activity锁(Stack来判断是个堆栈)
mMainStack.resumeTopActivityLocked(null);
}
}
/**
* Ensure that the top activity in the stack is resumed.
*
* @param prev The previously resumed activity, for when in the process
* of pausing; can be null to call from elsewhere.
*
* @return Returns true if something is being resumed, or false if
* nothing happened.
*/
final boolean resumeTopActivityLocked(ActivityRecord prev) {
// Find the first activity that is not finishing.
//获取顶部运行的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;
//系统刚启动next肯定是null
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
//到这里launcher就打开了,进入了桌面,启动了桌面
if (mMainStack) {
return mService.startHomeActivityLocked();
}
}
.
.
.
return true;
}