- 浏览: 82196 次
- 性别:
- 来自: 北京
最新评论
-
sunsenzhen:
线程用过不释放吗?
android多线程开发 -
grandkingwang:
...
android 文件上传(模拟表单提交) -
fategaga:
这是多线程么?
android多线程开发 -
zymsuper:
xmpp 的连接方式是 长连接吗?如果是,那和你之前写的第三种 ...
android实现推送实践 -
hyee:
哥们,你那个存储过程是基于哪个数据库的,据我所知Oracle的 ...
连载三:模拟JavaEye论坛首页存储过程
第一步:启动linux
1.Bootloader
2.Kernel
第二步android系统启动:入口为init.rc(system\core\rootdir)
1./system/bin/service manager: Binder 守护进程;
2.Runtime;
3.Zygote :app-process/app-main;
4.Start VM;
5.Start server
6.Start android service:Register to service Manager
7.Start Launcher
第三步:应用程序启动:运行package Manager
l Init进程
Android系统在启动时首先会启动Linux系统,引导加载Linux Kernel并启动init进程。Init进程是一个由内核启动的用户级进程,是Android系统的第一个进程。该进程的相关代码在platform\system\core\init\init.c。在main函数中,有如下代码:
open_devnull_stdio();
log_init();
INFO("reading config file\n");
init_parse_config_file("/init.rc");
/* pull the kernel commandline and ramdisk properties file in */
import_kernel_cmdline(0);
get_hardware_name(hardware, &revision);
snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
init_parse_config_file(tmp);
这里会加载解析init.rc和init.hardware.rc两个初始化脚本。*.rc文件定义了在init进程中需要启动哪些进程服务和执行哪些动作。其详细说明参见platform\system\core\init\reademe.txt。init.rc见如下定义:
service servicemanager /system/bin/servicemanager
user system
critical
onrestart restart zygote
onrestart restart media
service vold /system/bin/vold
socket vold stream 0660 root mount
ioprio be 2
service netd /system/bin/netd
socket netd stream 0660 root system
socket dnsproxyd stream 0660 root inet
service debuggerd /system/bin/debuggerd
service ril-daemon /system/bin/rild
socket rild stream 660 root radio
socket rild-debug stream 660 radio system
user root
group radio cache inet misc audio sdcard_rw
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
service drm /system/bin/drmserver
user drm
group system root inet
具体解析过程见platform\system\core\init\Init_parser.c。解析所得服务添加到service_list中,动作添加到action_list中。
接下来在main函数中执行动作和启动进程服务:
execute_one_command();
restart_processes()
通常init过程需要创建一些系统文件夹并启动USB守护进程、Android Debug Bridge守护进程、Debug守护进程、ServiceManager进程、Zygote进程等。
l ServiceManager进程
ServiceManager进程是所有服务的管理器。由init.rc对ServiceManager的描述service servicemanager /system/bin/servicemanager可知servicemanager进程从platform\frameworks\base\cmd\servicemanager\Service_manager.cpp启动。在main函数中有如下代码:
int main(int argc, char **argv)
{
struct binder_state *bs;
void *svcmgr = BINDER_SERVICE_MANAGER;
bs = binder_open(128*1024);
if (binder_become_context_manager(bs)) {
LOGE("cannot become context manager (%s)\n", strerror(errno));
return -1;
}
svcmgr_handle = svcmgr;
binder_loop(bs, svcmgr_handler);
return 0;
}
首先调用binder_open()打开Binder设备(/dev/binder),调用binder_become_context_manager()把当前进程设置为ServiceManager。ServiceManager本身就是一个服务。
int binder_become_context_manager(struct binder_state *bs)
{
return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);
}
最后binder_loop()进入循环状态,并设置svcmgr_handler回调函数等待添加、查询、获取服务等请求。
l Zygote进程
Zygote进程用于产生其他进程。由init.rc对zygote的描述service zygot /system/bin/app_process可知zygote进程从platfrom\frameworks\base\cmds\app_process\App_main.cpp启动。在main函数中有如下代码:
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);
} else {
set_process_name(argv0);
runtime.mClassName = arg;
// Remainder of args get passed to startup class main()
runtime.mArgC = argc-i;
runtime.mArgV = argv+i;
LOGV("App process is starting with pid=%d, class=%s.\n",
getpid(), runtime.getClassName());
runtime.start();
}
首先创建AppRuntime,即AndroidRuntime,建立了一个Dalvik虚拟机。通过这个runtime传递com.android.internal.os.ZygoteInit参数,从而由Dalvik虚拟机运行ZygoteInit.java的main(),开始创建Zygote进程。在其main()中,如下所示:
registerZygoteSocket();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preloadClasses();
//cacheRegisterMaps();
preloadResources();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
// Finish profiling the zygote initialization.
SamplingProfilerIntegration.writeZygoteSnapshot();
// Do an initial gc to clean up after startup
gc();
// If requested, start system server directly from Zygote
if (argv.length != 2) {
throw new RuntimeException(argv[0] + USAGE_STRING);
}
if (argv[1].equals("true")) {
startSystemServer();
} else if (!argv[1].equals("false")) {
throw new RuntimeException(argv[0] + USAGE_STRING);
}
首先通过registerZygoteSocket()登记端口,接着preloadClasses()装载相关类。这里大概要装载1000多个类,具体装载类见platform\frameworks\base\preloaded-classes。这个文件有WritePreloadedClassFile类自动生成。分析该类的main函数,有如下一段筛选类的代码:
// Preload classes that were loaded by at least 2 processes. Hopefully,
// the memory associated with these classes will be shared.
for (LoadedClass loadedClass : root.loadedClasses.values()) {
Set<String> names = loadedClass.processNames();
if (!Policy.isPreloadable(loadedClass)) {
continue;
}
if (names.size() >= MIN_PROCESSES ||
(loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {
toPreload.add(loadedClass);
}
}
int initialSize = toPreload.size();
System.out.println(initialSize
+ " classses were loaded by more than one app.");
// Preload eligable classes from applications (not long-running
// services).
for (Proc proc : root.processes.values()) {
if (proc.fromZygote() && !Policy.isService(proc.name)) {
for (Operation operation : proc.operations) {
LoadedClass loadedClass = operation.loadedClass;
if (shouldPreload(loadedClass)) {
toPreload.add(loadedClass);
}
}
}
}
其中MIN_LOAD_TIME_MICROS等于1250,当类的装载时间大于1.25ms,则需要预装载。
Policy.isPreloadable()定于如下:
/**Reports if the given class should be preloaded. */
public static boolean isPreloadable(LoadedClass clazz) {
return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);
}
其中EXCLUDED_CLASSES如下定义:
/**
* Classes which we shouldn't load from the Zygote.
*/
private static final Set<String> EXCLUDED_CLASSES
= new HashSet<String>(Arrays.asList(
// Binders
"android.app.AlarmManager",
"android.app.SearchManager",
"android.os.FileObserver",
"com.android.server.PackageManagerService$AppDirObserver",
// Threads
"android.os.AsyncTask",
"android.pim.ContactsAsyncHelper",
"java.lang.ProcessManager"
));
这几个Binders和Thread是不会被预加载的。
另外还有一些application需要装载,要求满足条件proc.fromZygote()且不是属于常驻内存的服务。SERVICES定义如下:
/**
* Long running services. These are restricted in their contribution to the
* preloader because their launch time is less critical.
*/
// TODO: Generate this automatically from package manager.
private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(
"system_server",
"com.google.process.content",
"android.process.media",
"com.android.bluetooth",
"com.android.calendar",
"com.android.inputmethod.latin",
"com.android.phone",
"com.google.android.apps.maps.FriendService", // pre froyo
"com.google.android.apps.maps:FriendService", // froyo
"com.google.android.apps.maps.LocationFriendService",
"com.google.android.deskclock",
"com.google.process.gapps",
"android.tts"
));
preloaded-classes是在下载源码的时候生成,WritePreloadedClassFile类并没有被用到,但可以通过这个类了解Android系统对预加载类的默认要求,参考修改preloaded-classes文件,减少开机初始化时要预加载的类,提高开机速度。
最后来通过startSystemServer()启动SystemServer进程。见如下代码:
/* 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",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
/*
* Enable debugging of the system process if *either* the command line flags
* indicate it should be debuggable or the ro.debuggable system property
* is set to "1"
*/
int debugFlags = parsedArgs.debugFlags;
if ("1".equals(SystemProperties.get("ro.debuggable")))
debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities)
Zygote包装了Linux的fork。forkSystemServer()调用forkAndSpecialize(),最终穿过虚拟机调用platform\dalvik\vm\native\dalvik_system_Zygote.c中Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的进程。
main()最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。
l SystemService进程
SystemService用于创建init.rc定义的服务之外的所有服务。在main()的最后有如下代码:
// 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);
System.loadLibrary("android_servers");
init1(args);
Init1()是在native空间实现的,用于启动native空间的服务,其实现在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
而system_init()服务初始化创建native层的各个服务:
// Start the sensor service
SensorService::instantiate();
// On the simulator, audioflinger et al don't get started the
// same way as on the device, and we need to start them here
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 services.\n");
runtime->callStatic("com/android/server/SystemServer", "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();
}
Init2启动一个线程,专门用来启动java空间的所有服务。如下代码所示启动部分服务:
Slog.i(TAG, "Content Manager");
ContentService.main(context,
factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
Slog.i(TAG, "Battery Service");
battery = new BatteryService(context);
ServiceManager.addService("battery", battery);
Slog.i(TAG, "Lights Service");
lights = new LightsService(context);
Slog.i(TAG, "Vibrator Service");
ServiceManager.addService("vibrator", new VibratorService(context));
// only initialize the power service after we have started the
// lights service, content providers and the battery service.
power.init(context, lights, ActivityManagerService.getDefault(), battery);
Slog.i(TAG, "Alarm Manager");
AlarmManagerService alarm = new AlarmManagerService(context);
ServiceManager.addService(Context.ALARM_SERVICE, alarm);
并且把这些服务添加到ServiceManager中,以便管理和进程间通讯。
在该线程后半部分,ActivityManagerService会等待AppWidget、WallPaper、IMM等systemReady后调用自身的systemReady()。
((ActivityManagerService)ServiceManager.getService("activity"))
.setWindowManager(wm);
// Skip Bluetooth if we have an emulator kernel
// TODO: Use a more reliable check to see if this product should
// support Bluetooth - see bug 988521
if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else {
Slog.i(TAG, "Bluetooth Service");
bluetooth = new BluetoothService(context);
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
bluetooth.initAfterRegistration();
bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
bluetoothA2dp);
int bluetoothOn = Settings.Secure.getInt(mContentResolver,
Settings.Secure.BLUETOOTH_ON, 0);
if (bluetoothOn > 0) {
bluetooth.enable();
}
}
而在ActivityManagerService的systemReady()最后会执行如下代码:
mMainStack.resumeTopActivityLocked(null);
由于Activity管理栈为空,因此启动Launcher。
www.2cto.com
// Find the first activity that is not finishing.
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;
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
return mService.startHomeActivityLocked();
}
}
在startHomeActivityLocked()中创建一个带Category为CATEGORY_HOME的Intent,由此去启动相应Activity,即Launcher。
Intent intent = new Intent(
mTopAction,
mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
这样,Android系统便启动起来进入到待机界面。
1.Bootloader
2.Kernel
第二步android系统启动:入口为init.rc(system\core\rootdir)
1./system/bin/service manager: Binder 守护进程;
2.Runtime;
3.Zygote :app-process/app-main;
4.Start VM;
5.Start server
6.Start android service:Register to service Manager
7.Start Launcher
第三步:应用程序启动:运行package Manager
l Init进程
Android系统在启动时首先会启动Linux系统,引导加载Linux Kernel并启动init进程。Init进程是一个由内核启动的用户级进程,是Android系统的第一个进程。该进程的相关代码在platform\system\core\init\init.c。在main函数中,有如下代码:
open_devnull_stdio();
log_init();
INFO("reading config file\n");
init_parse_config_file("/init.rc");
/* pull the kernel commandline and ramdisk properties file in */
import_kernel_cmdline(0);
get_hardware_name(hardware, &revision);
snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
init_parse_config_file(tmp);
这里会加载解析init.rc和init.hardware.rc两个初始化脚本。*.rc文件定义了在init进程中需要启动哪些进程服务和执行哪些动作。其详细说明参见platform\system\core\init\reademe.txt。init.rc见如下定义:
service servicemanager /system/bin/servicemanager
user system
critical
onrestart restart zygote
onrestart restart media
service vold /system/bin/vold
socket vold stream 0660 root mount
ioprio be 2
service netd /system/bin/netd
socket netd stream 0660 root system
socket dnsproxyd stream 0660 root inet
service debuggerd /system/bin/debuggerd
service ril-daemon /system/bin/rild
socket rild stream 660 root radio
socket rild-debug stream 660 radio system
user root
group radio cache inet misc audio sdcard_rw
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
service drm /system/bin/drmserver
user drm
group system root inet
具体解析过程见platform\system\core\init\Init_parser.c。解析所得服务添加到service_list中,动作添加到action_list中。
接下来在main函数中执行动作和启动进程服务:
execute_one_command();
restart_processes()
通常init过程需要创建一些系统文件夹并启动USB守护进程、Android Debug Bridge守护进程、Debug守护进程、ServiceManager进程、Zygote进程等。
l ServiceManager进程
ServiceManager进程是所有服务的管理器。由init.rc对ServiceManager的描述service servicemanager /system/bin/servicemanager可知servicemanager进程从platform\frameworks\base\cmd\servicemanager\Service_manager.cpp启动。在main函数中有如下代码:
int main(int argc, char **argv)
{
struct binder_state *bs;
void *svcmgr = BINDER_SERVICE_MANAGER;
bs = binder_open(128*1024);
if (binder_become_context_manager(bs)) {
LOGE("cannot become context manager (%s)\n", strerror(errno));
return -1;
}
svcmgr_handle = svcmgr;
binder_loop(bs, svcmgr_handler);
return 0;
}
首先调用binder_open()打开Binder设备(/dev/binder),调用binder_become_context_manager()把当前进程设置为ServiceManager。ServiceManager本身就是一个服务。
int binder_become_context_manager(struct binder_state *bs)
{
return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);
}
最后binder_loop()进入循环状态,并设置svcmgr_handler回调函数等待添加、查询、获取服务等请求。
l Zygote进程
Zygote进程用于产生其他进程。由init.rc对zygote的描述service zygot /system/bin/app_process可知zygote进程从platfrom\frameworks\base\cmds\app_process\App_main.cpp启动。在main函数中有如下代码:
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);
} else {
set_process_name(argv0);
runtime.mClassName = arg;
// Remainder of args get passed to startup class main()
runtime.mArgC = argc-i;
runtime.mArgV = argv+i;
LOGV("App process is starting with pid=%d, class=%s.\n",
getpid(), runtime.getClassName());
runtime.start();
}
首先创建AppRuntime,即AndroidRuntime,建立了一个Dalvik虚拟机。通过这个runtime传递com.android.internal.os.ZygoteInit参数,从而由Dalvik虚拟机运行ZygoteInit.java的main(),开始创建Zygote进程。在其main()中,如下所示:
registerZygoteSocket();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preloadClasses();
//cacheRegisterMaps();
preloadResources();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
// Finish profiling the zygote initialization.
SamplingProfilerIntegration.writeZygoteSnapshot();
// Do an initial gc to clean up after startup
gc();
// If requested, start system server directly from Zygote
if (argv.length != 2) {
throw new RuntimeException(argv[0] + USAGE_STRING);
}
if (argv[1].equals("true")) {
startSystemServer();
} else if (!argv[1].equals("false")) {
throw new RuntimeException(argv[0] + USAGE_STRING);
}
首先通过registerZygoteSocket()登记端口,接着preloadClasses()装载相关类。这里大概要装载1000多个类,具体装载类见platform\frameworks\base\preloaded-classes。这个文件有WritePreloadedClassFile类自动生成。分析该类的main函数,有如下一段筛选类的代码:
// Preload classes that were loaded by at least 2 processes. Hopefully,
// the memory associated with these classes will be shared.
for (LoadedClass loadedClass : root.loadedClasses.values()) {
Set<String> names = loadedClass.processNames();
if (!Policy.isPreloadable(loadedClass)) {
continue;
}
if (names.size() >= MIN_PROCESSES ||
(loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {
toPreload.add(loadedClass);
}
}
int initialSize = toPreload.size();
System.out.println(initialSize
+ " classses were loaded by more than one app.");
// Preload eligable classes from applications (not long-running
// services).
for (Proc proc : root.processes.values()) {
if (proc.fromZygote() && !Policy.isService(proc.name)) {
for (Operation operation : proc.operations) {
LoadedClass loadedClass = operation.loadedClass;
if (shouldPreload(loadedClass)) {
toPreload.add(loadedClass);
}
}
}
}
其中MIN_LOAD_TIME_MICROS等于1250,当类的装载时间大于1.25ms,则需要预装载。
Policy.isPreloadable()定于如下:
/**Reports if the given class should be preloaded. */
public static boolean isPreloadable(LoadedClass clazz) {
return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);
}
其中EXCLUDED_CLASSES如下定义:
/**
* Classes which we shouldn't load from the Zygote.
*/
private static final Set<String> EXCLUDED_CLASSES
= new HashSet<String>(Arrays.asList(
// Binders
"android.app.AlarmManager",
"android.app.SearchManager",
"android.os.FileObserver",
"com.android.server.PackageManagerService$AppDirObserver",
// Threads
"android.os.AsyncTask",
"android.pim.ContactsAsyncHelper",
"java.lang.ProcessManager"
));
这几个Binders和Thread是不会被预加载的。
另外还有一些application需要装载,要求满足条件proc.fromZygote()且不是属于常驻内存的服务。SERVICES定义如下:
/**
* Long running services. These are restricted in their contribution to the
* preloader because their launch time is less critical.
*/
// TODO: Generate this automatically from package manager.
private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(
"system_server",
"com.google.process.content",
"android.process.media",
"com.android.bluetooth",
"com.android.calendar",
"com.android.inputmethod.latin",
"com.android.phone",
"com.google.android.apps.maps.FriendService", // pre froyo
"com.google.android.apps.maps:FriendService", // froyo
"com.google.android.apps.maps.LocationFriendService",
"com.google.android.deskclock",
"com.google.process.gapps",
"android.tts"
));
preloaded-classes是在下载源码的时候生成,WritePreloadedClassFile类并没有被用到,但可以通过这个类了解Android系统对预加载类的默认要求,参考修改preloaded-classes文件,减少开机初始化时要预加载的类,提高开机速度。
最后来通过startSystemServer()启动SystemServer进程。见如下代码:
/* 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",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
/*
* Enable debugging of the system process if *either* the command line flags
* indicate it should be debuggable or the ro.debuggable system property
* is set to "1"
*/
int debugFlags = parsedArgs.debugFlags;
if ("1".equals(SystemProperties.get("ro.debuggable")))
debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities)
Zygote包装了Linux的fork。forkSystemServer()调用forkAndSpecialize(),最终穿过虚拟机调用platform\dalvik\vm\native\dalvik_system_Zygote.c中Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的进程。
main()最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。
l SystemService进程
SystemService用于创建init.rc定义的服务之外的所有服务。在main()的最后有如下代码:
// 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);
System.loadLibrary("android_servers");
init1(args);
Init1()是在native空间实现的,用于启动native空间的服务,其实现在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
而system_init()服务初始化创建native层的各个服务:
// Start the sensor service
SensorService::instantiate();
// On the simulator, audioflinger et al don't get started the
// same way as on the device, and we need to start them here
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 services.\n");
runtime->callStatic("com/android/server/SystemServer", "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();
}
Init2启动一个线程,专门用来启动java空间的所有服务。如下代码所示启动部分服务:
Slog.i(TAG, "Content Manager");
ContentService.main(context,
factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
Slog.i(TAG, "Battery Service");
battery = new BatteryService(context);
ServiceManager.addService("battery", battery);
Slog.i(TAG, "Lights Service");
lights = new LightsService(context);
Slog.i(TAG, "Vibrator Service");
ServiceManager.addService("vibrator", new VibratorService(context));
// only initialize the power service after we have started the
// lights service, content providers and the battery service.
power.init(context, lights, ActivityManagerService.getDefault(), battery);
Slog.i(TAG, "Alarm Manager");
AlarmManagerService alarm = new AlarmManagerService(context);
ServiceManager.addService(Context.ALARM_SERVICE, alarm);
并且把这些服务添加到ServiceManager中,以便管理和进程间通讯。
在该线程后半部分,ActivityManagerService会等待AppWidget、WallPaper、IMM等systemReady后调用自身的systemReady()。
((ActivityManagerService)ServiceManager.getService("activity"))
.setWindowManager(wm);
// Skip Bluetooth if we have an emulator kernel
// TODO: Use a more reliable check to see if this product should
// support Bluetooth - see bug 988521
if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
} else {
Slog.i(TAG, "Bluetooth Service");
bluetooth = new BluetoothService(context);
ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
bluetooth.initAfterRegistration();
bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
bluetoothA2dp);
int bluetoothOn = Settings.Secure.getInt(mContentResolver,
Settings.Secure.BLUETOOTH_ON, 0);
if (bluetoothOn > 0) {
bluetooth.enable();
}
}
而在ActivityManagerService的systemReady()最后会执行如下代码:
mMainStack.resumeTopActivityLocked(null);
由于Activity管理栈为空,因此启动Launcher。
www.2cto.com
// Find the first activity that is not finishing.
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;
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
return mService.startHomeActivityLocked();
}
}
在startHomeActivityLocked()中创建一个带Category为CATEGORY_HOME的Intent,由此去启动相应Activity,即Launcher。
Intent intent = new Intent(
mTopAction,
mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
这样,Android系统便启动起来进入到待机界面。
发表评论
-
android 跨进程访问service方法
2012-11-12 19:31 22561.Intent 启动service Activity方法集合 ... -
android画图-解锁界面
2012-11-13 22:43 2293锁屏 Launcher 输入法 应用程序开发 ... -
查询应用使用次数
2012-11-13 22:43 1995http://www.eoeandroid.com/fo ... -
分析Http请求头获取爱帮公交数据
2012-10-20 20:43 2758爱帮公交公布了自己的openAPI,但是之前自己不知道,就通 ... -
android 文件上传(模拟表单提交)
2012-10-15 22:52 15351package irdc.ex08_11; imp ... -
ActivityGroup 与TabActivity
2012-09-29 15:47 2016首先定义一个主布局 ... -
framework新增native方法,aidl,新类,新模块
2012-09-18 16:30 5085如何向android的framework里添加新类 goog ... -
android多线程开发
2012-08-31 12:22 74961.onResume()完全执行结束了(没有阻塞)的时候才会 ... -
FM 代码详解非原生
2012-09-21 23:40 3170FM点击关机按钮的时候: FMplay.java : ... -
Spreadtrum_Android_8805和8810环境搭建和源码编译V1.0.1_Word文档
2012-08-25 10:01 1693目 录 附录A 修改 ... -
adb问题汇总
2012-07-26 09:50 8151adb shell ps |grep "music| ... -
android Socket编程
2012-03-02 00:13 1159server: import java.net.*; ... -
android实现推送实践
2012-02-04 12:23 2146首先感谢 Android推送通 ... -
第一个iphone应用程序
2011-08-04 16:03 1116暑期实习已经 ... -
android http通信(二) 英译汉字典实例探究网络通信三种方法
2011-06-07 09:12 1470方法一:HttpURLConnection Stri ... -
android http通信(一) HttpURLConntection
2011-06-05 18:32 1195举例:从网络上下载图片 String urlpath=&qu ...
相关推荐
Android 11.0 开机启动流程介绍 本文档对 Android 11.0 平台开机启动流程进行了详细的介绍,涵盖了 Android 架构图、系统启动流程、init 启动流程、Zygote 启动流程、System Server 启动流程等关键部分。 Android ...
### Android开机启动流程详解 #### 一、概述 在探讨Android设备如何启动并准备好供用户使用的整个过程之前,我们先来简要回顾一下Android启动的基本流程。这一过程大致可以分为以下四个主要阶段: 1. **init进程...
在Android系统中,开机自启动应用是指当设备完成启动过程后,系统会自动运行的一类应用程序。这些应用通常会在用户无须手动干预的情况下执行特定任务,例如同步数据、推送通知或者进行后台服务的初始化。"BOOT_...
Android开机启动流程是指Android系统从加电到桌面出现的整个过程。这个过程可以分为八个阶段,每个阶段都有其特定的功能和作用。 阶段1:系统引导(bootloader) 在Android系统中,引导程序是系统启动的第一步。...
下面将详细讨论Android开机自启动的相关知识点。 1. **BroadcastReceiver**: 开机自启动的核心是`BroadcastReceiver`,这是一个可以监听系统广播事件的组件。Android系统在启动完成后会发送一个ACTION_BOOT_...
### Android开机启动流程详解 #### 一、系统引导(Bootloader) **1. 源码位置** - `bootable/bootloader/*` **2. 说明** - 加电后,CPU首先执行的是bootloader程序。在此阶段,根据用户的不同操作,可以进入...
Android开机启动流程是一个复杂的过程,涉及到多个组件和服务。下面是Android开机启动流程的详细解释: 1. 系统引导(bootloader) Android的开机流程始于引导程序bootloader。bootloader是Android系统的引导程序...
Android 开机动画启动过程详解, 方便定制自己的开机动画
Android 开机启动流程是一个复杂的过程,涉及到多个组件和服务。Zygote 是 Android 系统中最重要的后台程序之一,负责建立 Java Runtime,建立虚拟机和 Socket 接收 ActivityManagerService 的请求。System Server ...
下面将详细讲解Android开机自启动的工作原理、实现方法以及相关注意事项。 一、开机自启动的工作原理 Android系统在启动过程中会发送一系列系统级广播,其中就包括ACTION_BOOT_COMPLETED广播。当这个广播发出时,...
至于“开机启动应用”,Android系统会在启动过程中自动启动设置为开机启动的应用。开发者可以在应用的`AndroidManifest.xml`中为服务或接收器添加`android:enabled="true"`和`android:exported="true"`属性,并在`...
这个过程涉及到Android系统的权限管理和启动服务的配置。 1. **Delphi XE10**: Delphi是面向对象的Pascal编程语言的一个版本,由Embarcadero Technologies开发,用于Windows、macOS、iOS和Android平台。XE10是其中...
在Android系统中,Service是一种可以在后台长时间运行的组件,它不提供...以上就是关于Android开机自启动Service的实现细节,理解并掌握这些知识点对于开发者来说至关重要,特别是在设计需要在后台持续运行的应用时。
以上就是使用Delphi XE6为Android创建开机启动应用的基本步骤。通过理解Broadcast Receiver的工作原理和AndroidManifest.xml的配置,你可以实现更多类似的自定义行为。在实际开发中,还需要考虑不同Android版本的...
1. `logcat`:使用adb logcat命令查看系统日志,跟踪开机启动过程。 2. `adb shell am broadcast`:发送模拟的开机广播,测试BroadcastReceiver是否正常工作。 通过理解这些知识点,开发者可以更好地掌握Android...
首先,理解Android系统的启动流程至关重要。Android系统启动后,会执行系统级别的启动服务,然后依次启动各种核心服务。开发者可以通过创建一个BootReceiver(启动广播接收器)来监听系统启动完成的事件。当...
### Android开机启动流程详解 #### 一、系统引导(Bootloader) **1. 源码位置:** `bootable/bootloader/*` **2. 说明:** 当Android设备加电后,CPU首先执行的是Bootloader程序。Bootloader是整个启动过程中...