应用程序管理服务PackageManagerService安装应用程序的过程,其实就是解析析应用程序配置文件AndroidManifest.xml的过程,并从里面得到得到应用程序的相关信息,例如得到应用程序的组件Activity、Service、Broadcast Receiver和Content Provider等信息,有了这些信息后,通过ActivityManagerService这个服务,我们就可以在系统中正常地使用这些应用程序了。
应用程序管理服务PackageManagerService是系统启动的时候由SystemServer组件启动的,启后它就会执行应用程序安装的过程,因此,本文将从SystemServer启动PackageManagerService服务的过程开始分析系统中的应用程序安装的过程。
应用程序管理服务PackageManagerService从启动到安装应用程序的过程如下图所示:
下面我们具体分析每一个步骤。
Step 1. SystemServer.main
这个函数定义在frameworks/base/services/java/com/android/server/SystemServer.java文件中:
- publicclassSystemServer
- {
- ......
- nativepublicstaticvoidinit1(String[]args);
- ......
- publicstaticvoidmain(String[]args){
- ......
- init1(args);
- ......
- }
- ......
- }
Step 2. SystemServer.init1
这个函数是一个JNI方法,实现在frameworks/base/services/jni/com_android_server_SystemServer.cpp文件中:
- namespaceandroid{
- extern"C"intsystem_init();
- staticvoidandroid_server_SystemServer_init1(JNIEnv*env,jobjectclazz)
- {
- system_init();
- }
- staticJNINativeMethodgMethods[]={
- {"init1","([Ljava/lang/String;)V",(void*)android_server_SystemServer_init1},
- };
- intregister_android_server_SystemServer(JNIEnv*env)
- {
- returnjniRegisterNativeMethods
(env,"com/android/server/SystemServer", - gMethods,NELEM(gMethods));
- }
- };//namespaceandroid
Step 3.libsystem_server.system_init
函数system_init实现在libsystem_server库中,源代码位于frameworks/base/cmds/system_server/library/system_init.cpp文件中:
- extern"C"status_tsystem_init()
- {
- LOGI("Enteredsystem_init()");
- sp<ProcessState>proc(ProcessState::self());
- sp<IServiceManager>sm=defaultServiceManager();
- LOGI("ServiceManager:%p\n",sm.get());
- sp<GrimReaper>grim=newGrimReaper();
- sm->asBinder()->linkToDeath(grim,grim.get(),0);
- charpropBuf[PROPERTY_VALUE_MAX];
- property_get("system_init.startsurfaceflinger",propBuf,"1");
- if(strcmp(propBuf,"1")==0){
- //StarttheSurfaceFlinger
- SurfaceFlinger::instantiate();
- }
- //Startthesensorservice
- SensorService::instantiate();
- //Onthesimulator,audioflingeretaldon'tgetstartedthe
- //samewayasonthedevice,andweneedtostartthemhere
- if(!proc->supportsProcesses()){
- //StarttheAudioFlinger
- AudioFlinger::instantiate();
- //Startthemediaplaybackser
vice - MediaPlayerService::instantiate();
- //Startthecameraservice
- CameraService::instantiate();
- //Starttheaudiopolicyservi
ce - AudioPolicyService::instantiate();
- }
- //AndnowstarttheAndroidrun
time.Wehavetodothisbit - //ofnastinessbecausetheAnd
roidruntimeinitializatio nrequires - //someofthecoresystemservi
cestoalreadybestarted. - //Allotherserversshouldjus
tstarttheAndroidruntimea t - //thebeginningoftheirproce
sses'smain(),beforecalling - //theinitfunction.
- LOGI("Systemserver:startingAndroidruntime.\n");
- AndroidRuntime*runtime=AndroidRuntime::getRuntime();
- LOGI("Systemserver:startingAndroidservices.\n");
- runtime->callStatic("com/android/server/SystemServer","init2");
- //Ifrunninginourownprocess
,justgointothethread - //pool.Otherwise,calltheinitializationfin
ished - //functoletthisprocesscont
inueitsinitilization. - if(proc->supportsProcesses()){
- LOGI("Systemserver:enteringthreadpool.\n");
- ProcessState::self()->startThreadPool();
- IPCThreadState::self()->joinThreadPool();
- LOGI("Systemserver:exitingthreadpool.\n");
- }
- returnNO_ERROR;
- }
Step 4. AndroidRuntime.callStatic
这个函数定义在frameworks/base/core/jni/AndroidRuntime.cpp文件中:
- status_tAndroidRuntime::callStatic(constchar*className,constchar*methodName)
- {
- JNIEnv*env;
- jclassclazz;
- jmethodIDmethodId;
- env=getJNIEnv();
- if(env==NULL)
- returnUNKNOWN_ERROR;
- clazz=findClass(env,className);
- if(clazz==NULL){
- LOGE("ERROR:couldnotfindclass'%s'\n",className);
- returnUNKNOWN_ERROR;
- }
- methodId=env->GetStaticMethodID(clazz,methodName,"()V");
- if(methodId==NULL){
- LOGE("ERROR:couldnotfindmethod%s.%s\n",className,methodName);
- returnUNKNOWN_ERROR;
- }
- env->CallStaticVoidMethod(clazz,methodId);
- returnNO_ERROR;
- }
Step 5.SystemServer.init2
这个函数定义在frameworks/base/services/java/com/android/server/SystemServer.java文件中:
- publicclassSystemServer
- {
- ......
- publicstaticfinalvoidinit2(){
- Slog.i(TAG,"EnteredtheAndroidsystems
erver!"); - Threadthr=newServerThread();
- thr.setName("android.server.ServerThread");
- thr.start();
- }
- }
Step 6.ServerThread.run
这个函数定义在frameworks/base/services/java/com/android/server/SystemServer.java文件中:
- classServerThreadextendsThread{
- ......
- @Override
- publicvoidrun(){
- ......
- IPackageManagerpm=null;
- ......
- //Criticalservices...
- try{
- ......
- Slog.i(TAG,"PackageManager");
- pm=PackageManagerService.main(context,
- factoryTest!=SystemServer.FACTORY_TEST_OFF);
- ......
- }catch(RuntimeExceptione){
- Slog.e("System","Failurestartingcoreservi
ce",e); - }
- ......
- }
- ......
- }
Step 7.PackageManagerService.main
这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:
- classPackageManagerServiceext
endsIPackageManager.Stub{ - ......
- publicstaticfinalIPackageManagermain
(Contextcontext,booleanfactoryTest){ - PackageManagerServicem=newPackageManagerService(context,factoryTest);
- ServiceManager.addService("package",m);
- returnm;
- }
- ......
- }
在创建这个PackageManagerService服务实例时,会在PackageManagerService类的构造函数中开始执行安装应用程序的过程:
- classPackageManagerServiceextendsIPackageManager.Stub{
- ......
- publicPackageManagerService(Contextcontext,booleanfactoryTest){
- ......
- synchronized(mInstallLock){
- synchronized(mPackages){
- ......
- FiledataDir=Environment.getDataDirectory();
- mAppDataDir=newFile(dataDir,"data");
- mSecureAppDataDir=newFile(dataDir,"secure/data");
- mDrmAppPrivateInstallDir
=newFile(dataDir,"app-private"); - ......
- mFrameworkDir=newFile(Environment.getRootDirectory(),"framework");
- mDalvikCacheDir=newFile(dataDir,"dalvik-cache");
- ......
- //Findbaseframeworks(resourcepackageswithoutc
ode). - mFrameworkInstallObserve
r=newAppDirObserver( - mFrameworkDir.getPath(),OBSERVER_EVENTS,true);
- mFrameworkInstallObserve
r.startWatching(); - scanDirLI(mFrameworkDir,PackageParser.PARSE_IS_SYSTEM
- |PackageParser.PARSE_IS_SYSTEM_DIR,
- scanMode|SCAN_NO_DEX,0);
- //Collectallsystempackages
. - mSystemAppDir=newFile(Environment.getRootDirectory(),"app");
- mSystemInstallObserver=newAppDirObserver(
- mSystemAppDir.getPath(),OBSERVER_EVENTS,true);
- mSystemInstallObserver.startWatching();
- scanDirLI(mSystemAppDir,PackageParser.PARSE_IS_SYSTEM
- |PackageParser.PARSE_IS_SYSTEM_DIR,scanMode,0);
- //Collectallvendorpackages
. - mVendorAppDir=newFile("/vendor/app");
- mVendorInstallObserver=newAppDirObserver(
- mVendorAppDir.getPath(),OBSERVER_EVENTS,true);
- mVendorInstallObserver.startWatching();
- scanDirLI(mVendorAppDir,PackageParser.PARSE_IS_SYSTEM
- |PackageParser.PARSE_IS_SYSTEM_DIR,scanMode,0);
- mAppInstallObserver=newAppDirObserver(
- mAppInstallDir.getPath(),OBSERVER_EVENTS,false);
- mAppInstallObserver.startWatching();
- scanDirLI(mAppInstallDir,0,scanMode,0);
- mDrmAppInstallObserver=newAppDirObserver(
- mDrmAppPrivateInstallDir
.getPath(),OBSERVER_EVENTS,false); - mDrmAppInstallObserver.startWatching();
- scanDirLI(mDrmAppPrivateInstallDir
,PackageParser.PARSE_FORWARD_LOCK, - scanMode,0);
- ......
- }
- }
- }
- ......
- }
/system/framework
/system/app
/vendor/app
/data/app
/data/app-private
Step 8.PackageManagerService.scanDirLI
这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:
- classPackageManagerServiceextendsIPackageManager.Stub{
- ......
- privatevoidscanDirLI(Filedir,intflags,intscanMode,longcurrentTime){
- String[]files=dir.list();
- ......
- inti;
- for(i=0;i<files.length;i++){
- Filefile=newFile(dir,files[i]);
- if(!isPackageFilename(files[i])){
- //Ignoreentrieswhicharenot
apk's - continue;
- }
- PackageParser.Packagepkg=scanPackageLI(file,
- flags|PackageParser.PARSE_MUST_BE_APK,scanMode,currentTime);
- //Don'tmessaroundwithappsinsys
tempartition. - if(pkg==null&&(flags&PackageParser.PARSE_IS_SYSTEM)==0&&
- mLastScanError==PackageManager.INSTALL_FAILED_INVALID_APK){
- //Deletetheapk
- Slog.w(TAG,"Cleaningupfailedinstallo
f"+file); - file.delete();
- }
- }
- }
- ......
- }
Step 9.PackageManagerService.scanPackageLI
这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:
- classPackageManagerServiceextendsIPackageManager.Stub{
- ......
- privatePackageParser.PackagescanPackageLI(FilescanFile,
- intparseFlags,intscanMode,longcurrentTime){
- ......
- StringscanPath=scanFile.getPath();
- parseFlags|=mDefParseFlags;
- PackageParserpp=newPackageParser(scanPath);
- ......
- finalPackageParser.Packagepkg=pp.parsePackage(scanFile,
- scanPath,mMetrics,parseFlags);
- ......
- returnscanPackageLI(pkg,parseFlags,scanMode|SCAN_UPDATE_SIGNATURE,currentTime);
- }
- ......
- }
Step 10.PackageParser.parsePackage
这个函数定义在frameworks/base/core/java/android/content/pm/PackageParser.java文件中:
- publicclassPackageParser{
- ......
- publicPackageparsePackage(FilesourceFile,StringdestCodePath,
- DisplayMetricsmetrics,intflags){
- ......
- mArchiveSourcePath=sourceFile.getPath();
- ......
- XmlResourceParserparser=null;
- AssetManagerassmgr=null;
- booleanassetError=true;
- try{
- assmgr=newAssetManager();
- intcookie=assmgr.addAssetPath(mArchiveSourcePath);
- if(cookie!=0){
- parser=assmgr.openXmlResourceParser(cookie,"AndroidManifest.xml");
- assetError=false;
- }else{
- ......
- }
- }catch(Exceptione){
- ......
- }
- ......
- String[]errorText=newString[1];
- Packagepkg=null;
- ExceptionerrorException=null;
- try{
- //XXXXtodo:needtofigureoutcorrectco
nfiguration. - Resourcesres=newResources(assmgr,metrics,null);
- pkg=parsePackage(res,parser,flags,errorText);
- }catch(Exceptione){
- ......
- }
- ......
- parser.close();
- assmgr.close();
- //Setcodeandresourcepaths
- pkg.mPath=destCodePath;
- pkg.mScanPath=mArchiveSourcePath;
- //pkg.applicationInfo.sourceDir=destCodePath;
- //pkg.applicationInfo.publicSourceDir=destRes;
- pkg.mSignatures=null;
- returnpkg;
- }
- ......
- }
- publicclassPackageParser{
- ......
- privatePackageparsePackage(
- Resourcesres,XmlResourceParserparser,intflags,String[]outError)
- throwsXmlPullParserException,IOException{
- ......
- StringpkgName=parsePackageName(parser,attrs,flags,outError);
- ......
- finalPackagepkg=newPackage(pkgName);
- ......
- inttype;
- ......
- TypedArraysa=res.obtainAttributes(attrs,
- com.android.internal.R.styleable.AndroidManifest);
- ......
- while((type=parser.next())!=parser.END_DOCUMENT
- &&(type!=parser.END_TAG||parser.getDepth()>outerDepth)){
- if(type==parser.END_TAG||type==parser.TEXT){
- continue;
- }
- StringtagName=parser.getName();
- if(tagName.equals("application")){
- ......
- if(!parseApplication(pkg,res,parser,attrs,flags,outError)){
- returnnull;
- }
- }elseif(tagName.equals("permission-group")){
- ......
- }elseif(tagName.equals("permission")){
- ......
- }elseif(tagName.equals("permission-tree")){
- ......
- }elseif(tagName.equals("uses-permission")){
- ......
- }elseif(tagName.equals("uses-configuration")){
- ......
- }elseif(tagName.equals("uses-feature")){
- ......
- }elseif(tagName.equals("uses-sdk")){
- ......
- }elseif(tagName.equals("supports-screens")){
- ......
- }elseif(tagName.equals("protected-broadcast")){
- ......
- }elseif(tagName.equals("instrumentation")){
- ......
- }elseif(tagName.equals("original-package")){
- ......
- }elseif(tagName.equals("adopt-permissions")){
- ......
- }elseif(tagName.equals("uses-gl-texture")){
- ......
- }elseif(tagName.equals("compatible-screens")){
- ......
- }elseif(tagName.equals("eat-comment")){
- ......
- }elseif(RIGID_PARSER){
- ......
- }else{
- ......
- }
- }
- ......
- returnpkg;
- }
- ......
- }