Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android應用框架之PackageManagerService

Android應用框架之PackageManagerService

編輯:關於Android編程

系統在啟動的時候會啟動一個叫做PackageManagerService的服務,顧名思義,這個服務主要管理安裝在設備上的應用程序,其中最為重要的工作就是在在系統啟動之後,PackageManagerService會掃描特定目錄下地以apk為後綴的文件,然後將對應的應用安裝到系統中。注意,這裡的安裝並不是我們平時所說的安裝,它指的的是將存放在磁盤之上的靜態應用程序文件進行解析,並將相關信息注冊到系統中。而具體的解析工作實際就是讀取應用的配置文件manifest.xml,並將文件中配置的組件
(Activity,Service,BroadcastRecevier,ContentProvider),權限等信息注冊到PackageManagerService中。
本篇博客主要介紹PackageManagerService的啟動過程,以及PackageManagerService如何安裝各個應用程序。

1.PackageManagerService啟動過程

和ActivityManagerService,WindowManagerService一樣,PackageManagerService是一個系統級的服務,運行在獨立的進程中,而所有的系統級服務都是由SystemServer啟動的。所以首先來看看SystemServer的啟動過程。

1) SystemServer啟動:

SystemServer組件是由Zygote進程負責啟動的,啟動的時候就會調用它的main函數,這個函數主要調用了JNI方法init1來做一些系統初始化的工作。

public class SystemServer
{
    ......
    native public static void init1(String[] args);
    ......
    public static void main(String[] args) {
        ......
        init1(args);
        ......
    }
    ......
}
2)SystemServer.system_init

經過一系列調用後轉到system_init方法,這是一個JNI方法

extern "C" status_t system_init()
{
    LOGI("Entered system_init()");
    sp proc(ProcessState::self());
    sp sm = defaultServiceManager();
    LOGI("ServiceManager: %p\n", sm.get());
    sp grim = new GrimReaper();
    sm->asBinder()->linkToDeath(grim, grim.get(), 0);
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsurfaceflinger", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }

    // 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();
    }

    // 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");
    runtime->callStatic("com/android/server/SystemServer", "init2");

    // If running in our own process, just go into the thread
    // pool.  Otherwise, call the initialization finished
    // func to let this process continue its initilization.
    if (proc->supportsProcesses()) {
        LOGI("System server: entering thread pool.\n");
        ProcessState::self()->startThreadPool();
        IPCThreadState::self()->joinThreadPool();
        LOGI("System server: exiting thread pool.\n");
    }

    return NO_ERROR;
}

在這個方法中,創建了SurfaceFlinger、SensorService、AudioFlinger、MediaPlayerService、CameraService和AudioPolicyService這幾個服務,然後就通過系統全局唯一的AndroidRuntime實例變量runtime的callStatic來調用SystemServer的init2函數了。init2函數很簡單,創建一個線程,而PackageManagerService就是在這個線程中創建的。

public class SystemServer
{
    ......
    public static final void init2() {
        Slog.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start();
    }
}
3)ServerThread.run
class ServerThread extends Thread {
    ......
    @Override
    public void run() {
        ......
        IPackageManager pm = null;
        ......
        // Critical services...
        try {
            ......
            Slog.i(TAG, "Package Manager");
            pm = PackageManagerService.main(context,
                        factoryTest != SystemServer.FACTORY_TEST_OFF);
            ......
        } catch (RuntimeException e) {
            Slog.e("System", "Failure starting core service", e);
        }
        ......
    }
    ......
}

在這個線程中創建了PackageManagerService,並同時啟動了其main函數。另外在這個線程中還啟動了ActivityManagerService等其他Service

2.應用安裝

接下來再來看看PackageManagerService啟動之後如何進行應用程序的安裝。

1)PackageManagerService.main
class PackageManagerService extends IPackageManager.Stub {
    ......
    public static final IPackageManager main(Context context, boolean factoryTest) {
        PackageManagerService m = new PackageManagerService(context, factoryTest);
        ServiceManager.addService("package", m);
        return m;
    }
    ......
}

可以看到,創建完成後,就加載到ServiceManager中。接下來看看PackageManagerService的構造函數:

class PackageManagerService extends IPackageManager.Stub {
    ......

    public PackageManagerService(Context context, boolean factoryTest) {
        ......

        synchronized (mInstallLock) {
            synchronized (mPackages) {
                ......

                File dataDir = Environment.getDataDirectory();
                mAppDataDir = new File(dataDir, "data");
                mSecureAppDataDir = new File(dataDir, "secure/data");
                mDrmAppPrivateInstallDir = new File(dataDir, "app-private");

                ......

                mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
                mDalvikCacheDir = new File(dataDir, "dalvik-cache");

                ......

                // Find base frameworks (resource packages without code).
                mFrameworkInstallObserver = new AppDirObserver(
                mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
                mFrameworkInstallObserver.startWatching();
                scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
                    | PackageParser.PARSE_IS_SYSTEM_DIR,
                    scanMode | SCAN_NO_DEX, 0);

                // Collect all system packages.
                mSystemAppDir = new File(Environment.getRootDirectory(), "app");
                mSystemInstallObserver = new AppDirObserver(
                    mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
                mSystemInstallObserver.startWatching();
                scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);

                // Collect all vendor packages.
                mVendorAppDir = new File("/vendor/app");
                mVendorInstallObserver = new AppDirObserver(
                    mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
                mVendorInstallObserver.startWatching();
                scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);


                mAppInstallObserver = new AppDirObserver(
                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
                mAppInstallObserver.startWatching();
                scanDirLI(mAppInstallDir, 0, scanMode, 0);

                mDrmAppInstallObserver = new AppDirObserver(
                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
                mDrmAppInstallObserver.startWatching();
                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
                    scanMode, 0);

                ......
            }
        }
    }

    ......
}

可以看到,在構造函數中,PackageManagerService(PMS)會掃描特定目錄下的APK文件,然後進行相關的加載工作,這些目錄包括:

/system/framework
/system/app
/vendor/app
/data/app
/data/app-private

在每個路徑下,都調用了scanDirLI函數,接下來看看對應的函數做了些什麼。

2)PackageParser.parsePackage

scanDirLI中又經過多次調用,具體就是掃描對應目錄的文件,如果是apk文件,就找到apk文件中的manifest文件,最後再為每一個apk創建一個PackageParser對象,並將manifest文件傳遞給PackageParser.parsePackage。

public class PackageParser {
    ......

    private Package parsePackage(
            Resources res, XmlResourceParser parser, int flags, String[] outError)
            throws XmlPullParserException, IOException {
        ......

        String pkgName = parsePackageName(parser, attrs, flags, outError);

        ......

        final Package pkg = new Package(pkgName);

        ......

        int type;

        ......

        TypedArray sa = 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;
                }

                String tagName = parser.getName();
                if (tagName.equals("application")) {
                    ......

                    if (!parseApplication(pkg, res, parser, attrs, flags, outError)) {
                        return null;
                    }
                } else if (tagName.equals("permission-group")) {
                    ......
                } else if (tagName.equals("permission")) {
                    ......
                } else if (tagName.equals("permission-tree")) {
                    ......
                } else if (tagName.equals("uses-permission")) {
                    ......
                } else if (tagName.equals("uses-configuration")) {
                    ......
                } else if (tagName.equals("uses-feature")) {
                    ......
                } else if (tagName.equals("uses-sdk")) {
                    ......
                } else if (tagName.equals("supports-screens")) {
                    ......
                } else if (tagName.equals("protected-broadcast")) {
                    ......
                } else if (tagName.equals("instrumentation")) {
                    ......
                } else if (tagName.equals("original-package")) {
                    ......
                } else if (tagName.equals("adopt-permissions")) {
                    ......
                } else if (tagName.equals("uses-gl-texture")) {
                    ......
                } else if (tagName.equals("compatible-screens")) {
                    ......
                } else if (tagName.equals("eat-comment")) {
                    ......
                } else if (RIGID_PARSER) {
                    ......
                } else {
                    ......
                }
        }

        ......

        return pkg;
    }

    ......
        private Package parsePackage(
            Resources res, XmlResourceParser parser, int flags, String[] outError)
            throws XmlPullParserException, IOException {
        ......

        String pkgName = parsePackageName(parser, attrs, flags, outError);

        ......

        final Package pkg = new Package(pkgName);

        ......

        int type;

        ......

        TypedArray sa = 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;
                }

                String tagName = parser.getName();
                if (tagName.equals("application")) {
                    ......

                    if (!parseApplication(pkg, res, parser, attrs, flags, outError)) {
                        return null;
                    }
                } else if (tagName.equals("permission-group")) {
                    ......
                } else if (tagName.equals("permission")) {
                    ......
                } else if (tagName.equals("permission-tree")) {
                    ......
                } else if (tagName.equals("uses-permission")) {
                    ......
                } else if (tagName.equals("uses-configuration")) {
                    ......
                } else if (tagName.equals("uses-feature")) {
                    ......
                } else if (tagName.equals("uses-sdk")) {
                    ......
                } else if (tagName.equals("supports-screens")) {
                    ......
                } else if (tagName.equals("protected-broadcast")) {
                    ......
                } else if (tagName.equals("instrumentation")) {
                    ......
                } else if (tagName.equals("original-package")) {
                    ......
                } else if (tagName.equals("adopt-permissions")) {
                    ......
                } else if (tagName.equals("uses-gl-texture")) {
                    ......
                } else if (tagName.equals("compatible-screens")) {
                    ......
                } else if (tagName.equals("eat-comment")) {
                    ......
                } else if (RIGID_PARSER) {
                    ......
                } else {
                    ......
                }
        }

        ......

        return pkg;
    }

    ......
}

這裡就是對AndroidManifest.xml文件中的application標簽進行解析了,我們常用到的標簽就有activity、service、receiver和provider,這裡解析完成後,一層層返回,調用另一個版本的scanPackageLI函數把來解析後得到的應用程序信息保存下來。

<code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code><code>class PackageManagerService extends IPackageManager.Stub {
    ......

    // Keys are String (package name), values are Package.  This also serves
    // as the lock for the global state.  Methods that must be called with
    // this lock held have the prefix "LP".
    final HashMap<string, packageparser.package=""> mPackages =
        new HashMap<string, packageparser.package="">();

    ......

    // All available activities, for your resolving pleasure.
    final ActivityIntentResolver mActivities =
    new ActivityIntentResolver();

    // All available receivers, for your resolving pleasure.
    final ActivityIntentResolver mReceivers =
        new ActivityIntentResolver();

    // All available services, for your resolving pleasure.
    final ServiceIntentResolver mServices = new ServiceIntentResolver();

    // Keys are String (provider class name), values are Provider.
    final HashMap<componentname, packageparser.provider=""> mProvidersByComponent =
        new HashMap<componentname, packageparser.provider="">();

    ......

    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
            int parseFlags, int scanMode, long currentTime) {
        ......

        synchronized (mPackages) {
            ......

            // Add the new setting to mPackages
            mPackages.put(pkg.applicationInfo.packageName, pkg);

            ......

            int N = pkg.providers.size();
            int i;
            for (i=0; i<n; packageparser.provider="" p="pkg.providers.get(i);" p.info.processname="fixProcessName(pkg.applicationInfo.processName," new="" ......="" n="pkg.services.size();" for="" i="0;" packageparser.service="" s="pkg.services.get(i);" s.info.processname="fixProcessName(pkg.applicationInfo.processName," r="null;" packageparser.activity="" a="pkg.receivers.get(i);" a.info.processname="fixProcessName(pkg.applicationInfo.processName," return="" pre="">

到這裡整個應用的安裝過程就介紹完了。其實整個過程還是很明確,清晰的。 接下來再來總結一下整個啟動過程:

Zygote—>啟動SystemServer—>啟動ServerThread—>啟動PackageManagerService—>掃描特定目錄下的apk文件,進行加載—>解析APK的manifest文件,將配置信息加載到PackageManagerService中

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved