第一篇:Android系統(tǒng)啟動源代碼調查分析
Android系統(tǒng)啟動調查。
目的:Android程序入口在哪里?Mainifest配置文件如何加載實例化?從系統(tǒng)層到應用層如何使用?
目標從系統(tǒng)角度來了解Android啟動過程,通過下載源代碼并且根據(jù)源代碼從底層開始跟蹤,跟著方法走一遍Android啟動過程。了解Zygote進程是什么?
開機一開始:Linux啟動這一層,主要包括了兩塊:BootLoader(嵌入式系統(tǒng)的引導程序)和Kernel(Linux內核層,驅動層)第二塊:Android系統(tǒng)啟動。
我們都知道,Linux系統(tǒng)啟動,定義了一個Init.rc這個系統(tǒng)啟動的配置文件(放在System/bin文件下面)。
Init.rc啟動的時候,最開始啟動了SystemManager守護進程,它的源代碼是一個Java文件,守護進程是一個與界面無關,會持續(xù)運行在后臺,用來接收響應,并且維持系統(tǒng)運營的。
在啟動servicemanager的同時,再來啟動Zygote,Zygote實際上啟動的是:app_main.cpp的系統(tǒng)文件.這個文件的main()方法,會調用Android_Runtime.cpp的文件中的start()方法,這個方法通過JNI機制,來調用ZygoteInit.java孵化器初始文件,這個文件的Main()函數(shù),將會去調用所有進程。
這個ZygoteInit文件的main()函數(shù),這個函數(shù)通過JNI機制調用了FrameWrok中的SystemServer文件,這個文件有三個函數(shù):main(),init1()和init2()方法。
Init1()方法會通過JNI機制再去調用com_Android__server_SystemService.java的原生態(tài)文件,去實現(xiàn)系統(tǒng)初始化的操作,(調用System_init.cpp)。
當系統(tǒng)初始化工作做完之后,系統(tǒng)反過來會調用SystemServer文件下面的init2()方法,會通過runtime方法調用ServerThread進程去調用激活其他的所有進程。
第三塊:應用程序啟動(下次再講)。
使用工具:【代碼分析工具】source Insight 【源代碼】 Android 源代碼包
操作步驟:
在下載好Android SDK 安裝包之后(如果沒有下載好請移步這里)
【配置代碼分析工具】
打開source Insight 軟件,來配置Android源代碼。
“項目”→“新建項目”
在“新項目名”填寫:“Android 14”(Android 第14個版本,代表Android V4.0.3)在“項目文件儲存位置”填寫:SDK源代碼包的位置
繼續(xù)進行配置,點擊確定。
選中右邊的所有文件夾,點擊“添加所有”按鈕,將這個版本的源代碼全部導入。
應用級別:選中將所有的子集目錄,下級子目錄中的所有文件都導入查找項目。
進行檢索。。。
一共找到了“213720”個文件,是否導入?選中“Yes”
導入文件,索引建立
這時候,查看正下方,項目文件(213720)已經(jīng)全部導入,項目準備完畢。可以進行調查了。
這時候你看到的右邊工具欄,就是我們可以用來方便查找的搜索欄,輸入對應的關鍵字即可。
切入正題,查找Android系統(tǒng)啟動文件
【查找Init文件】啟動方法會初始化MainiFest.xml配置文件,配置文件再去調用里面的配置,但是啟動方法何時啟動的調查,還未找到源頭,只知道一切事物的源頭,從這里開始。
原代碼如下:
service console /system/bin/sh(啟動Linux內核)
console
disabled
user shell
group log
on property:ro.secure=0
start console
# adbd is controlled by the persist.service.adb.enable system property service adbd /sbin/adbd
disabled
# adbd on at boot in emulator on property:ro.kernel.qemu=1
start adbd
on property:persist.service.adb.enable=1
start adbd
on property:persist.service.adb.enable=0
stop adbd
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
OK,現(xiàn)在先調查(ServerManager)這個啟動進程。
在system/core/libsysutils/src 目錄下(系統(tǒng)級啟動進程)
(啟動孵化器進程)
在左側點擊start方法
這就是守護進程中的源代碼之一,start()方法 ServiceManager::ServiceManager(){ } int ServiceManager::start(const char *name){ //如果進程已經(jīng)啟動,那么打印日志:“XX進程已經(jīng)啟動”
if(isRunning(name)){
SLOGW(“Service '%s' is already running”, name);
return 0;
}
SLOGD(“Starting service '%s'”, name);
property_set(“ctl.start”, name);
int count = 200;
while(count--){
sched_yield();
if(isRunning(name))
break;
}
if(!count){
SLOGW(“Timed out waiting for service '%s' to start”, name);
errno = ETIMEDOUT;
return-1;
}
SLOGD(“Sucessfully started '%s'”, name);
return 0;}
再來看同時啟動的app_main的源代碼,我們去查看一下它的main函數(shù)
int main(int argc, const char* const argv[]){
// These are global variables in ProcessState.cpp
mArgC = argc;
mArgV = argv;
mArgLen = 0;
for(int i=0;i mArgLen += strlen(argv[i])+ 1; } mArgLen--; AppRuntime runtime; const char *arg; const char *argv0; argv0 = argv[0]; // Process command line arguments // ignore argv[0] argc--; argv++; // Everything up to '--' or first non '-' arg goes to the vm int i = runtime.addVmArguments(argc, argv); // Next arg is parent directory if(i < argc){ runtime.mParentDir = argv[i++]; } // Next arg is startup classname or “--zygote” 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”); //設置了一個進程名叫zygote的進程,通過runtime來啟動ZygoteInit文件中的startSystemServer方法 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(); } } else { LOG_ALWAYS_FATAL(“app_process: no class name or--zygote supplied.”); fprintf(stderr, “Error: no class name or--zygote supplied.n”); app_usage(); return 10; } } 調查一下runtime的類。AppRuntime,這就是android系統(tǒng)的運行時類,它啟動了zygote孵化器進程,用來孵化Davlik虛擬機的。 runtime.start(“com.android.internal.os.ZygoteInit”,startSystemServer);所涉及到的ZygoteInit文件。 找到ZygoteInit文件(FrameWork里面的一個java類)。先去看看Main函數(shù)。 public static void main(String argv[]){ try { VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024); // Start profiling the zygote initialization.SamplingProfilerIntegration.start(); 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”)){ //如果輸入?yún)?shù)為真,我們就啟動系統(tǒng)服務 startSystemServer(); } else if(!argv[1].equals(“false”)){ throw new RuntimeException(argv[0] + USAGE_STRING); } Log.i(TAG, “Accepting command socket connections”); if(ZYGOTE_FORK_MODE){ //如果孵化器一直是交叉模式,就啟動運行交叉模式函數(shù);否則就選擇另一個循環(huán)模式 runForkMode(); } else { runSelectLoopMode(); } closeServerSocket(); } catch(MethodAndArgsCaller caller){ caller.run(); } catch(RuntimeException ex){ Log.e(TAG, “Zygote died with exception”, ex); closeServerSocket(); throw ex; } } 我們繼續(xù)查看,如果參數(shù)為真的情況下,ZygoteInit文件中的,startSystemServer()函數(shù)的源代碼。 /** * 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”,“--capabilities=130104352,130104352”,“--runtime-init”,“--nice-name=system_server”,“com.android.server.SystemServer”,//這個虛擬機的名字叫system Server }; 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); } catch(IllegalArgumentException ex){ throw new RuntimeException(ex); } /* For child process */ if(pid == 0){ handleSystemServerProcess(parsedArgs); } return true; } 我們繼續(xù)去查看 system Server的源代碼 main函數(shù): /** * 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);//Init1()函數(shù)卻是個空函數(shù) public static void main(String[] args){ if(System.currentTimeMillis()< EARLIEST_SUPPORTED_TIME){ // If a device's clock is before 1970(before 0), a lot of // APIs crash dealing with negative numbers, notably // java.io.File#setLastModified, so instead we fake it and // hope that time from cell towers or NTP fixes it // shortly.Slog.w(TAG, “System clock is before 1970;setting to 1970.”); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } if(SamplingProfilerIntegration.isEnabled()){ SamplingProfilerIntegration.start(); timer = new Timer(); timer.schedule(new TimerTask(){ @Override public void run(){ SamplingProfilerIntegration.writeSnapshot(“system_server”); } }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL); } // 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);// main()函數(shù)中,會調用到 init1()的方法。 } public static final void init2(){ Slog.i(TAG, “Entered the Android system server!”); Thread thr = new ServerThread(); thr.setName(“android.server.ServerThread”); thr.start(); } 因為通過調查發(fā)現(xiàn),SystemServer文件的main()函數(shù)調用的init1()函數(shù),是一個空方法,native public static void init1(String[] args); 但是根據(jù)JNI調用機制,我們可以在同名文件夾(framework/base/services/)下找到JNL目錄,然后找到和系統(tǒng)相關的com_android_server_SystemServer.java文件 使用“C”的動態(tài)鏈接嗲用system_init 的方法。它去回調Init2的方法 我們繼續(xù)看看SystemServer方法的Init2()方法是看什么用的。 去調查一下ServerThread()方法是干什么用的?這個內部類ServerThread就是啟動,并且實例化每一個系統(tǒng)進程的線程類 class ServerThread extends Thread { private static final String TAG = “SystemServer”; private final static boolean INCLUDE_DEMO = false; private static final int LOG_BOOT_PROGRESS_SYSTEM_RUN = 3010; private ContentResolver mContentResolver; private class AdbSettingsObserver extends ContentObserver { public AdbSettingsObserver(){ super(null); } @Override public void onChange(boolean selfChange){ boolean enableAdb =(Settings.Secure.getInt(mContentResolver,Settings.Secure.ADB_ENABLED, 0)> 0); // setting this secure property will start or stop adbd SystemProperties.set(“persist.service.adb.enable”, enableAdb ? “1” : “0”); } } @Override public void run(){ EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,SystemClock.uptimeMillis()); Looper.prepare(); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND); BinderInternal.disableBackgroundScheduling(true); android.os.Process.setCanSelfBackground(false); // Check whether we failed to shut down last time we tried.{ final String shutdownAction = SystemProperties.get(ShutdownThread.SHUTDOWN_ACTION_PROPERTY, “"); if(shutdownAction!= null && shutdownAction.length()> 0){ boolean reboot =(shutdownAction.charAt(0)== '1'); final String reason; if(shutdownAction.length()> 1){ reason = shutdownAction.substring(1, shutdownAction.length()); } else { reason = null; } ShutdownThread.rebootOrShutdown(reboot, reason); } } String factoryTestStr = SystemProperties.get(”ro.factorytest“); int factoryTest = ”“.equals(factoryTestStr)? SystemServer.FACTORY_TEST_OFF : Integer.parseInt(factoryTestStr); LightsService lights = null; PowerManagerService power = null; BatteryService battery = null; ConnectivityService connectivity = null; IPackageManager pm = null; Context context = null; WindowManagerService wm = null; BluetoothService bluetooth = null; BluetoothA2dpService bluetoothA2dp = null; HeadsetObserver headset = null; DockObserver dock = null; UsbService usb = null; UiModeManagerService uiMode = null; RecognitionManagerService recognition = null; ThrottleService throttle = null; // Critical services...try { Slog.i(TAG, ”Entropy Service“); ServiceManager.addService(”entropy“, new EntropyService()); Slog.i(TAG, ”Power Manager“); power = new PowerManagerService(); ServiceManager.addService(Context.POWER_SERVICE, power); Slog.i(TAG, ”Activity Manager“); context = ActivityManagerService.main(factoryTest); Slog.i(TAG, ”Telephony Registry“); ServiceManager.addService(”telephony.registry“, new TelephonyRegistry(context)); AttributeCache.init(context); Slog.i(TAG, ”Package Manager“); pm = PackageManagerService.main(context,factoryTest!= SystemServer.FACTORY_TEST_OFF); ActivityManagerService.setSystemProcess(); mContentResolver = context.getContentResolver(); // The AccountManager must come before the ContentService try { Slog.i(TAG, ”Account Manager“); ServiceManager.addService(Context.ACCOUNT_SERVICE,new AccountManagerService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Account Manager“, e); } 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); Slog.i(TAG, ”Init Watchdog“); Watchdog.getInstance().init(context, battery, power, alarm,ActivityManagerService.self()); Slog.i(TAG, ”Window Manager“); wm = WindowManagerService.main(context, power,factoryTest!= SystemServer.FACTORY_TEST_LOW_LEVEL); ServiceManager.addService(Context.WINDOW_SERVICE, wm); ((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(); } } } catch(RuntimeException e){ Slog.e(”System“, ”Failure starting core service“, e); } DevicePolicyManagerService devicePolicy = null; StatusBarManagerService statusBar = null; InputMethodManagerService imm = null; AppWidgetService appWidget = null; NotificationManagerService notification = null; WallpaperManagerService wallpaper = null; LocationManagerService location = null; if(factoryTest!= SystemServer.FACTORY_TEST_LOW_LEVEL){ try { Slog.i(TAG, ”Device Policy“); devicePolicy = new DevicePolicyManagerService(context); ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy); } catch(Throwable e){ Slog.e(TAG, ”Failure starting DevicePolicyService“, e); } try { Slog.i(TAG, ”Status Bar“); statusBar = new StatusBarManagerService(context); ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar); } catch(Throwable e){ Slog.e(TAG, ”Failure starting StatusBarManagerService“, e); } try { Slog.i(TAG, ”Clipboard Service“); ServiceManager.addService(Context.CLIPBOARD_SERVICE,new ClipboardService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Clipboard Service“, e); } try { Slog.i(TAG, ”Input Method Service“); imm = new InputMethodManagerService(context, statusBar); ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Input Manager Service“, e); } try { Slog.i(TAG, ”NetStat Service“); ServiceManager.addService(”netstat“, new NetStatService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting NetStat Service“, e); } try { Slog.i(TAG, ”NetworkManagement Service“); ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE,NetworkManagementService.create(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting NetworkManagement Service“, e); } try { Slog.i(TAG, ”Connectivity Service“); connectivity = ConnectivityService.getInstance(context); ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Connectivity Service“, e); } try { Slog.i(TAG, ”Throttle Service“); throttle = new ThrottleService(context); ServiceManager.addService(Context.THROTTLE_SERVICE, throttle); } catch(Throwable e){ Slog.e(TAG, ”Failure starting ThrottleService“, e); } try { Slog.i(TAG, ”Accessibility Manager“); ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,new AccessibilityManagerService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Accessibility Manager“, e); } try { /* * NotificationManagerService is dependant on MountService,*(for media / usb notifications)so we must start MountService first.*/ Slog.i(TAG, ”Mount Service“); ServiceManager.addService(”mount“, new MountService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Mount Service“, e); } try { Slog.i(TAG, ”Notification Manager“); notification = new NotificationManagerService(context, statusBar, lights); ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Notification Manager“, e); } try { Slog.i(TAG, ”Device Storage Monitor“); ServiceManager.addService(DeviceStorageMonitorService.SERVICE,new DeviceStorageMonitorService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting DeviceStorageMonitor service“, e); } try { Slog.i(TAG, ”Location Manager“); location = new LocationManagerService(context); ServiceManager.addService(Context.LOCATION_SERVICE, location); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Location Manager“, e); } try { Slog.i(TAG, ”Search Service“); ServiceManager.addService(Context.SEARCH_SERVICE,new SearchManagerService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Search Service“, e); } if(INCLUDE_DEMO){ Slog.i(TAG, ”Installing demo data...“); (new DemoThread(context)).start(); } try { Slog.i(TAG, ”DropBox Service“); ServiceManager.addService(Context.DROPBOX_SERVICE,new DropBoxManagerService(context, new File(”/data/system/dropbox“))); } catch(Throwable e){ Slog.e(TAG, ”Failure starting DropBoxManagerService“, e); } try { Slog.i(TAG, ”Wallpaper Service“); wallpaper = new WallpaperManagerService(context); ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Wallpaper Service“, e); } try { Slog.i(TAG, ”Audio Service“); ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context)); } catch(Throwable e){ Slog.e(TAG, ”Failure starting Audio Service“, e); } try { Slog.i(TAG, ”Headset Observer“); // Listen for wired headset changes headset = new HeadsetObserver(context); } catch(Throwable e){ Slog.e(TAG, ”Failure starting HeadsetObserver“, e); } try { Slog.i(TAG, ”Dock Observer“); // Listen for dock station changes dock = new DockObserver(context, power); } catch(Throwable e){ Slog.e(TAG, ”Failure starting DockObserver“, e); } try { Slog.i(TAG, ”USB Service“); // Listen for USB changes usb = new UsbService(context); ServiceManager.addService(Context.USB_SERVICE, usb); } catch(Throwable e){ Slog.e(TAG, ”Failure starting UsbService“, e); } try { Slog.i(TAG, ”UI Mode Manager Service"); Android 應用調查: 分類:系統(tǒng)工具,社交,音樂視頻,瀏覽器輸入法,交通地圖,購物娛樂,閱讀資訊,拍照,詞典,主題桌面,健康,通信,辦公,理財,其它 1.系統(tǒng)工具: 360衛(wèi)士,QQ手機管家,墨跡天氣,ES文件瀏覽器,手機LED燈,Go鎖屏,海桌HiaPa,金山電池醫(yī)生,LEB安全大師,語音360… 2.社交:手機QQ,微博,微信,世紀佳緣,人人,飛信,米聊,開心網(wǎng),騰訊微 博,手機旺旺,MSN,朋友網(wǎng),手機百合,豆瓣,facebook….3.音樂視頻:天天動聽,奇藝,手機電視,Adobe Flash,酷狗音樂播放器,酷我音 樂2012,PPS播放器,手機暴風影音,QQ音樂,QQ影音,QvodPlay,優(yōu)酷,土豆,騰訊視頻,youtube,芒果TV….4.瀏覽器輸入法: UC,手機瀏覽器,搜狗輸入法,百度輸入法,QQ輸入法,Google 輸入法,百度瀏覽器... 5.交通地圖:Google地圖,百度地圖,盛名時刻表,ATM位置通,深圳地鐵… 6.購物娛樂:京東,美團,當當,手機支付寶,趕集,拉手,58同城,凡客,QQ 財付通,樂淘….7.閱讀資訊:QQ手機閱讀,鳳凰閱讀,新浪閱讀,網(wǎng)易閱讀,中關村在線,掌上 書庫,百度文庫….8.拍照:360手機攝影,9.詞典:有道,新華,金山,Google翻譯,同聲翻譯,天天英語….10.主題桌面:360,go桌面,91手機桌面,Go鎖屏,Go主題… 11.健康:通信,辦公,理財,其它 Android 應用開發(fā)需求: 95%都是公司內部產(chǎn)品上面,需要手機客戶端支持, 本章講述Struts2的工作原理。 讀者如果曾經(jīng)學習過Struts1.x或者有過Struts1.x的開發(fā)經(jīng)驗,那么千萬不要想當然地以為這一章可以跳過。實際上Struts1.x與Struts2并無我們想象的血緣關系。雖然Struts2的開發(fā)小組極力保留Struts1.x的習慣,但因為Struts2的核心設計完全改變,從思想到設計到工作流程,都有了很大的不同。 Struts2是Struts社區(qū)和WebWork社區(qū)的共同成果,我們甚至可以說,Struts2是WebWork的升級版,他采用的正是WebWork的核心,所以,Struts2并不是一個不成熟的產(chǎn)品,相反,構建在WebWork基礎之上的Struts2是一個運行穩(wěn)定、性能優(yōu)異、設計成熟的WEB框架。 本章主要對Struts的源代碼進行分析,因為Struts2與WebWork的關系如此密不可分,因此,讀者需要下載xwork的源代碼,訪問http://文件,則通過過濾器鏈繼續(xù)往下傳送,直到到達請求的資源為止。 如果getMapping()方法返回有效的ActionMapping對象,則被認為正在請求某個Action,將調用Dispatcher.serviceAction(request, response, servletContext, mapping)方法,該方法是處理Action的關鍵所在。上述過程的源代碼如清單15所示。 代碼清單15:FilterDispatcher.doFilter()方法 publicvoid doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException { HttpServletRequest request =(HttpServletRequest)req; HttpServletResponse response =(HttpServletResponse)res; ServletContext servletContext = getServletContext(); String timerKey = “FilterDispatcher_doFilter: ”; try { UtilTimerStack.push(timerKey); request = prepareDispatcherAndWrapRequest(request, response);//重新包裝request ActionMapping mapping; try { mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());//得到存儲Action信息的ActionMapping對象 } catch(Exception ex){ ……(省略部分代碼) return; } if(mapping == null){//如果mapping為null,則認為不是請求Action資源 String resourcePath = RequestUtils.getServletPath(request); if(“".equals(resourcePath)&& null!= request.getPathInfo()){ resourcePath = request.getPathInfo(); } { ngth()); //如果請求的資源以/struts開頭,則當作靜態(tài)資源處理 if(serveStatic && resourcePath.startsWith(”/struts“)) String name = resourcePath.substring(”/struts“.le findStaticResource(name, request, response);} else { //否則,過濾器鏈繼續(xù)往下傳遞 chain.doFilter(request, response);} // The framework did its job here return; } //如果請求的資源是Action,則調用serviceAction方法。 dispatcher.serviceAction(request, response, servletContext, mapping); } finally { try { ActionContextCleanUp.cleanUp(req); } } finally { UtilTimerStack.pop(timerKey); } } 這段代碼的活動圖如圖18所示: (圖18) 在Dispatcher.serviceAction()方法中,先加載Struts2的配置文件,如果沒有人為配置,則默認加載struts-default.xml、struts-plugin.xml和struts.xml,并且將配置信息保存在形如com.opensymphony.xwork2.config.entities.XxxxConfig的類中。 類com.opensymphony.xwork2.config.providers.XmlConfigurationProvider負責配置文件的讀取和解析,addAction()方法負責讀取 代碼清單16:XmlConfigurationProvider.addPackage()方法 protected PackageConfig addPackage(Element packageElement)throws ConfigurationException { PackageConfig newPackage = buildPackageContext(packageElement); age if(newPackage.isNeedsRefresh()){ return newPackage;} if(LOG.isDebugEnabled()){ LOG.debug(”Loaded “ + newPackage);} // add result types(and default result)to this package addResultTypes(newPackage, packageElement);// load the interceptors and interceptor stacks for this packloadInterceptors(newPackage, packageElement);// load the default interceptor reference for this package loadDefaultInterceptorRef(newPackage, packageElement);// load the default class ref for this package loadDefaultClassRef(newPackage, packageElement);// load the global result list for this package loadGlobalResults(newPackage, packageElement);// load the global exception handler list for this package loadGlobalExceptionMappings(newPackage, packageElement); // get actions NodeList actionList = packageElement.getElementsByTagName(”action“); for(int i = 0;i < actionList.getLength();i++){ Element actionElement =(Element)actionList.item(i); addAction(actionElement, newPackage); } // load the default action reference for this package loadDefaultActionRef(newPackage, packageElement); configuration.addPackageConfig(newPackage.getName(), newPackage); return newPackage; } 活動圖如圖19所示: (圖19) 配置信息加載完成后,創(chuàng)建一個Action的代理對象——ActionProxy引用,實際上對Action的調用正是通過ActionProxy實現(xiàn)的,而ActionProxy又由ActionProxyFactory創(chuàng)建,ActionProxyFactory是創(chuàng)建ActionProxy的工廠。 注:ActionProxy和ActionProxyFactory都是接口,他們的默認實現(xiàn)類分別是DefaultActionProxy和DefaultActionProxyFactory,位于com.opensymphony.xwork2包下。 在這里,我們絕對有必要介紹一下com.opensymphony.xwork2.DefaultActionInvocation類,該類是對ActionInvocation接口的默認實現(xiàn),負責Action和截攔器的執(zhí)行。 在DefaultActionInvocation類中,定義了invoke()方法,該方法實現(xiàn)了截攔器的遞歸調用和執(zhí)行Action的execute()方法。其中,遞歸調用截攔器的代碼如清單17所示: 代碼清單17:調用截攔器,DefaultActionInvocation.invoke()方法的部分代碼 if(interceptors.hasNext()){ //從截攔器集合中取出當前的截攔器 final InterceptorMapping interceptor =(InterceptorMapping)interceptors.next(); UtilTimerStack.profile(”interceptor: “+interceptor.getName(),new UtilTimerStack.ProfilingBlock public String doProfiling()throws Exception { //執(zhí)行截攔器(Interceptor)接口中定義的intercept方法 resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); returnnull; } }); } 從代碼中似乎看不到截攔器的遞歸調用,其實是否遞歸完全取決于程序員對程序的控制,先來看一下Interceptor接口的定義: 代碼清單18:Interceptor.java publicinterface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation)throws Exception;} 所有的截攔器必須實現(xiàn)intercept方法,而該方法的參數(shù)恰恰又是ActionInvocation,所以,如果在intercept方法中調用invocation.invoke(),代碼清單17會再次執(zhí)行,從Action的Intercepor列表中找到下一個截攔器,依此遞歸。下面是一個自定義截攔器示例: 代碼清單19:CustomIntercepter.java publicclass CustomIntercepter extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation)throws Exception } { actionInvocation.invoke();return”李贊紅“;} 截攔器的調用活動圖如圖20所示: (圖20) 如果截攔器全部執(zhí)行完畢,則調用invokeActionOnly()方法執(zhí)行Action,invokeActionOnly()方法基本沒做什么工作,只調用了invokeAction()方法。 為了執(zhí)行Action,必須先創(chuàng)建該對象,該工作在DefaultActionInvocation的構造方法中調用init()方法早早完成。調用過程是:DefaultActionInvocation()->init()->createAction()。創(chuàng)建Action的代碼如下: 代碼清單20:DefaultActionInvocation.createAction()方法 protectedvoid createAction(Map contextMap){ try { action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap); } catch(InstantiationException e){ ……異常代碼省略 } } Action創(chuàng)建好后,輪到invokeAction()大顯身手了,該方法比較長,但關鍵語句實在很少,用心點看不會很難。 代碼清單20:DefaultActionInvocation.invokeAction()方法 protected String invokeAction(Object action, ActionConfig actionConfig)throws Exception { //獲取Action中定義的execute()方法名稱,實際上該方法是可以隨便定義的 String methodName = proxy.getMethod(); String timerKey = ”invokeAction: “+proxy.getActionName(); try { UtilTimerStack.push(timerKey); Method method; try { //將方法名轉化成Method對象 method = getAction().getClass().getMethod(methodName, new Class[0]); } catch(NoSuchMethodException e){ // hmm--OK, try doXxx instead try { //如果Method出錯,則嘗試在方法名前加do,再轉成Method對象 String altMethodName = ”do“ + methodName.substring(0, 1).toUpperCase()+ methodName.substring(1); method = getAction().getClass().getMethod(altMethodName, new Class[0]); } catch(NoSuchMethodException e1){ // throw the original one throw e; } } //執(zhí)行方法 [0]); } Object methodResult = method.invoke(action, new Object //處理跳轉 if(methodResult instanceof Result){ this.result =(Result)methodResult; returnnull; } else { return(String)methodResult; } } catch(NoSuchMethodException e){ ……省略異常代碼 } finally { UtilTimerStack.pop(timerKey);} 剛才使用了一段插述,我們繼續(xù)回到ActionProxy類。 我們說Action的調用是通過ActionProxy實現(xiàn)的,其實就是調用了ActionProxy.execute()方法,而該方法又調用了ActionInvocation.invoke()方法。歸根到底,最后調用的是DefaultActionInvocation.invokeAction()方法。 以下是調用關系圖: 其中: ? ActionProxy:管理Action的生命周期,它是設置和執(zhí)行Action的起始點。 ? ActionInvocation:在ActionProxy層之下,它表示了Action的執(zhí)行狀態(tài)。它持有Action實例和所有的Interceptor 以下是serviceAction()方法的定義: 代碼清單21:Dispatcher.serviceAction()方法 publicvoid serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping)throws ServletException { Map // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action ValueStack stack =(ValueStack)request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); if(stack!= null){ extraContext.put(ActionContext.VALUE_STACK, ValueStackFactory.getFactory().createValueStack(stack)); } String timerKey = ”Handling request from Dispatcher“; try { UtilTimerStack.push(timerKey); String namespace = mapping.getNamespace(); String name = mapping.getName(); String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, extraContext, true, false); proxy.setMethod(method); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); // if the ActionMapping says to go straight to a result, do it! if(mapping.getResult()!= null){ Result result = mapping.getResult(); result.execute(proxy.getInvocation()); } else { proxy.execute(); } // If there was a previous value stack then set it back onto the request if(stack!= null){ request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack); } } catch(ConfigurationException e){ LOG.error(”Could not find action or result", e); sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e); } catch(Exception e){ thrownew ServletException(e); } finally { UtilTimerStack.pop(timerKey); } } 最后,通過Result完成頁面的跳轉。 3.4 本小節(jié)總結 總體來講,Struts2的工作機制比Struts1.x要復雜很多,但我們不得不佩服Struts和WebWork開發(fā)小組的功底,代碼如此優(yōu)雅,甚至能夠感受看到兩個開發(fā)小組心神相通的默契。兩個字:佩服。 以下是Struts2運行時調用方法的順序圖: (圖21) 四、總結 閱讀源代碼是一件非常辛苦的事,對讀者本身的要求也很高,一方面要有扎實的功底,另一方面要有超強的耐力和恒心。本章目的就是希望能幫助讀者理清一條思路,在必要的地方作出簡單的解釋,達到事半功倍的效果。 當然,筆者不可能為讀者解釋所有類,這也不是我的初衷。Struts2+xwork一共有700余類,除了為讀者做到現(xiàn)在的這些,已無法再做更多的事情。讀者可以到Struts官方網(wǎng)站下載幫助文檔,慢慢閱讀和理解,相信會受益頗豐。 本章并不適合java語言初學者或者對java博大精深的思想理解不深的讀者閱讀,這其中涉及到太多的術語和類的使用,特別不要去鉆牛角尖,容易使自信心受損。基本搞清楚Struts2的使用之后,再回過頭來閱讀本章,對一些知識點和思想也許會有更深的體會。 如果讀者的java功底比較渾厚,而且對Struts2充滿興趣,但又沒太多時間研究,不妨仔細閱讀本章,再對照Struts的源代碼,希望對您有所幫助。 1)植被數(shù)量多,種類較豐富,但缺少大喬木.初到學校的學生,對校園綠化是很容易滿意的,卻不能長久關注,是學校在植物更新等方面做的還不夠。與15題呼應 2)顏色是大多數(shù)人對于事物,特別是景觀的第一感受(景觀設計中應注重季相設計),而隨著生活質量的日益提高,音樂和植物在景觀布置中也更加受到重視(可以作聲景觀)。氣味的設計容易被人忽略,但一旦出現(xiàn)就會成為人們接近或離開某個地方的最主要因素。 3)夏天花多反而讓人覺得亂,沒有頭緒,秋天,校園里花楸、衛(wèi)矛成主景(其他季節(jié)景觀設計應加強)。 4)針對農業(yè)院校而設立的題型(現(xiàn)在校園作物收獲后,大片空地荒廢,影響景觀)(可在外圍適當種灌木圍合、遮擋) 5)說明人們更喜歡新鮮奇特的東西。與10、12題呼應 6)通過這題說明了在進行設計時因充分考慮其功能性。車輛的高分貝噪聲對學生學習的影響很大,在設計中應盡量避免學校周圍的交通干道,校園內車輛應慢行。與8題呼應 7)有些蟲子會使草地更顯自然,本題的選項會反映出一個人的個性,說明性格對景觀的使用也是有影響的。 8)車輛、人行和高分貝的音樂噪音對學生學習的影響很大,在設計中應盡量避免學校周圍的交通干道,校園內車輛應慢行。在學生公寓附近的道路做到人流分散。增加建筑的隔音效果的同時進行噪音污染的教育。(舒緩的音樂,鳥鳴等可以使人放松、安神,可在休閑廣場適當應用創(chuàng)造聲景) 9)選擇會依心情而定,可在密林中空出一片草地,可以滿足不同需要的人,也可使選②(私密性強)的人豁然開朗。 10)符合大學生自由、開放、熱情、喜歡不受拘束的天性。 11)與私密性、對個人空間的要求和東方人的性格有關,還有就是東西方文化的差異。 12)功能也是選擇樹種的一個重要方面。 13)人們都有好奇的天性,看到有圍觀,自然會圍上去,只是希望美景不會讓人失望。還要能做到能吸引游人,引人駐足的景觀十分重要(要具有生態(tài)效應)。 14)綠色是自然的象征,是植物的主色調(占地面積大)。不同的顏色帶給人不同的心情,適當運用各種顏色,創(chuàng)造帶給游客不同感覺的景。 15)一方面:大學校園在環(huán)境保護方面相對完善,基本滿足了人們的的需要。 另一方面:在國內,人們在環(huán)境保護方面意識還不夠強烈,了解較少,不夠全面。 廈門手機開發(fā)培訓Android手機模式分析 第一部分其實游戲就是廈門博看文思讓狀態(tài)機不斷的讓Canvas在View上畫你想要的東西。這個狀態(tài)機包括內部的執(zhí)行,還包括外部的輸入。 Android開發(fā)的MVC模式 1,通過View和SurfaceView來顯示界面的視圖。(處理界面與用戶的交互事件,如,觸筆點擊,用戶按鍵等??赏ㄟ^View類的onKeyDown,onKeyUp,onTouchEvent等)。 2,用Activity來控制游戲的整體結構。 3,設計一個邏輯類,用來處理邏輯運算。 Android中任何一個View類都只有重寫onDraw方法來實現(xiàn)界面顯示。 Android中提供了 onKeyUp,onKeyDown,onKeyMultiple,onKeyPreIme,onTouchEvent,onTrackballEvent等方法??梢杂脕硖幚碛螒蛑械氖录?。所以繼承View時,需要重載這些方法。Android中提供了invalidate來刷新界面,但invalidate不能直接在線程中調用,違背單線程模型。 因此Android中最常用的方法是利用Handler來時更新UI界面。 第一部分View類 每個View類都有一個繪畫的畫布,在游戲中可以自定義視圖View,任何一個View類都只需要重寫onDraw方法來實現(xiàn)界面顯示,可以是3D,也可以是文本。 游戲的核心就是不斷的繪圖和刷新,圖我們可以通過onDraw方法繪制,刷新 Android中可以用invalidate方法來刷新界面,注意:invalidate不能直接在線程中調用,因其違背了 違背單線程模型。因此Android中最常用的方法是廈門博看文思利用Handler來時更新UI界面。下面這個例子中包含了兩個刷新方法。第二篇:Android 應用調查.doc
第三篇:struts2源代碼分析(個人覺得非常經(jīng)典)
第四篇:調查分析
第五篇:廈門手機開發(fā)培訓Android手機模式分析