为了账号安全,请及时绑定邮箱和手机立即绑定

Android应用程序安装过程解析(源码角度)(中篇)

标签:
Java Android
3.常见的4种安装场景
1.系统应用安装――开机时完成,没有安装界面
2.网络下载应用安装――通过market应用完成,没有安装界面
3.ADB工具安装――没有安装界面。
4.第三方应用安装――通过SD卡里的APK文件安装,有安装界面,由 packageinstaller.apk应用处理安装及卸载过程的界面。

安装过程:

复制APK安装包到data/app目录下,解压并扫描安装包,把dex文件(Dalvik字节码)保存到dalvik-cache目录,并data/data目录下创建对应的应用数据目录。

卸载过程:

删除安装过程中在上述三个目录下创建的文件及目录。

(1)系统应用安装――开机时完成,没有安装界面

PackageManagerService处理各种应用的安装,卸载,管理等工作,开机时由systemServer启动此服务

在创建这个PackageManagerService服务实例时,会在PackageManagerService类的构造函数中开始执行安装应用程序的过程:

PackageManagerService核心代码

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

    public PackageManagerService(Context context, boolean factoryTest) {  
        ......  
    mSetting = new Setting();
        synchronized (mInstallLock) {  
            synchronized (mPackages) {  
                ......  

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

        mRestoredSetting = mASetting.readLP();

                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);  

                ......  
        final boolean regrantPermissions = mSetting.mInternalSDKplatform != mSdkVersion;
        updatePermissionsLP(null,null,true,rregrantPermissions .regrantPermissions );
        msetting.writeLP();
            }  
        }  
    }  

    ......  
}  
这里会调用scanDirLI函数来扫描移动设备上的下面这五个目录中的Apk文件
    /system/framework

    /system/app

    /vendor/app

    /data/app

    /data/app-private

由于Android每次启动的时候都需要安装一次信息,但是有些信息是保持不变的,例如Linux用户组Id,PackageManagerService 每次安装程序之后,都会把这些程序的信息保存下来,以便下次使用,
恢复上一次程序的安装信息是通过PackageManagerService 的成员变量mSetting的readLP()来实现的,恢复信息之后就开始扫描和安装app了。

扫描安装app
PackageManagerService.scanDirLI

这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:


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

    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {  
        String[] files = dir.list();  
        ......  

        int i;  
        for (i=0; i<files.length; i++) {  
            File file = new File(dir, files[i]);  
            if (!isPackageFilename(files[i])) {  
                // Ignore entries which are not apk's  
                continue;  
            }  
            PackageParser.Package pkg = scanPackageLI(file,  
                flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);  
            // Don't mess around with apps in system partition.  
            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&  
                mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {  
                    // Delete the apk  
                    Slog.w(TAG, "Cleaning up failed install of " + file);  
                    file.delete();  
            }  
        }  
    }  

    ......  
}  

对于目录中的每一个文件,如果是以后Apk作为后缀名,那么就调用scanPackageLI函数来对它进行解析和安装。

PackageManagerService.scanPackageLI

这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:


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

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

        String scanPath = scanFile.getPath();  
        parseFlags |= mDefParseFlags;  
        PackageParser pp = new PackageParser(scanPath);  

        ......  

        final PackageParser.Package pkg = pp.parsePackage(scanFile,  
            scanPath, mMetrics, parseFlags);  

        ......  

        return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);  
    }  

    ......  
}  

这个函数首先会为这个Apk文件创建一个PackageParser实例,接着调用这个实例的parsePackage函数来对这个Apk文件进行解析。这个函数最后还会调用另外一个版本的scanPackageLI函数把来解析后得到的应用程序信息保存在PackageManagerService中。

PackageParser.parsePackage

这个函数定义在frameworks/base/core/java/android/content/pm/PackageParser.java文件中:

public class PackageParser {  
    ......  

    public Package parsePackage(File sourceFile, String destCodePath,  
            DisplayMetrics metrics, int flags) {  
        ......  

        mArchiveSourcePath = sourceFile.getPath();  

        ......  

        XmlResourceParser parser = null;  
        AssetManager assmgr = null;  
        boolean assetError = true;  
        try {  
            assmgr = new AssetManager();  
            int cookie = assmgr.addAssetPath(mArchiveSourcePath);  
            if(cookie != 0) {  
                parser = assmgr.openXmlResourceParser(cookie, "AndroidManifest.xml");  
                assetError = false;  
            } else {  
                ......  
            }  
        } catch (Exception e) {  
            ......  
        }  

        ......  

        String[] errorText = new String[1];  
        Package pkg = null;  
        Exception errorException = null;  
        try {  
            // XXXX todo: need to figure out correct configuration.  
            Resources res = new Resources(assmgr, metrics, null);  
            pkg = parsePackage(res, parser, flags, errorText);  
        } catch (Exception e) {  
            ......  
        }  

        ......  

        parser.close();  
        assmgr.close();  

        // Set code and resource paths  
        pkg.mPath = destCodePath;  
        pkg.mScanPath = mArchiveSourcePath;  
        //pkg.applicationInfo.sourceDir = destCodePath;  
        //pkg.applicationInfo.publicSourceDir = destRes;  
        pkg.mSignatures = null;  

        return pkg;  
    }  

    ......  
}  

每一个Apk文件都是一个归档文件,它里面包含了Android应用程序的配置文件AndroidManifest.xml,这里主要就是要对这个配置文件就行解析了,从Apk归档文件中得到这个配置文件后,就调用另一外版本的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;  
    }  

    ......  
}  

这里就是对AndroidManifest.xml文件中的各个标签进行解析了,各个标签的含义可以参考官方文档http://developer.android.com/guide/topics/manifest/manifest-intro.html,这里我们只简单看一下application标签的解析,这是通过调用parseApplication函数来进行的。

PackageParser.parseApplication

这个函数定义在frameworks/base/core/java/android/content/pm/PackageParser.java文件中:

public class PackageParser {  
    ......  

    private boolean parseApplication(Package owner, Resources res,  
            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)  
            throws XmlPullParserException, IOException {  
        final ApplicationInfo ai = owner.applicationInfo;  
        final String pkgName = owner.applicationInfo.packageName;  

        TypedArray sa = res.obtainAttributes(attrs,  
            com.android.internal.R.styleable.AndroidManifestApplication);  

        ......  

        int type;  
        while ((type=parser.next()) != parser.END_DOCUMENT  
            && (type != parser.END_TAG || parser.getDepth() > innerDepth)) {  
                if (type == parser.END_TAG || type == parser.TEXT) {  
                    continue;  
                }  

                String tagName = parser.getName();  
                if (tagName.equals("activity")) {  
                    Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false);  
                    ......  

                    owner.activities.add(a);  

                } else if (tagName.equals("receiver")) {  
                    Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true);  
                    ......  

                    owner.receivers.add(a);  
                } else if (tagName.equals("service")) {  
                    Service s = parseService(owner, res, parser, attrs, flags, outError);  
                    ......  

                    owner.services.add(s);  
                } else if (tagName.equals("provider")) {  
                    Provider p = parseProvider(owner, res, parser, attrs, flags, outError);  
                    ......  

                    owner.providers.add(p);  
                } else if (tagName.equals("activity-alias")) {  
                    Activity a = parseActivityAlias(owner, res, parser, attrs, flags, outError);  
                    ......  

                    owner.activities.add(a);  
                } else if (parser.getName().equals("meta-data")) {  
                    ......  
                } else if (tagName.equals("uses-library")) {  
                    ......  
                } else if (tagName.equals("uses-package")) {  
                    ......  
                } else {  
                    ......  
                }  
        }  

        return true;  
    }  

    ......  
}  

这里就是对AndroidManifest.xml文件中的application标签进行解析了,我们常用到的标签就有activity、service、receiver和provider,各个标签的含义可以参考官方文档http://developer.android.com/guide/topics/manifest/manifest-intro.html。这里解析完成后,一层层返回到Step 9中,调用另一个版本的scanPackageLI函数把来解析后得到的应用程序信息保存下来。

PackageManagerService.scanPackageLI

这个函数定义在frameworks/base/services/java/com/android/server/PackageManagerService.java文件中:


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; i++) {  
                PackageParser.Provider p = pkg.providers.get(i);  
                p.info.processName = fixProcessName(pkg.applicationInfo.processName,  
                    p.info.processName, pkg.applicationInfo.uid);  
                mProvidersByComponent.put(new ComponentName(p.info.packageName,  
                    p.info.name), p);  

                ......  
            }  

            N = pkg.services.size();  
            for (i=0; i<N; i++) {  
                PackageParser.Service s = pkg.services.get(i);  
                s.info.processName = fixProcessName(pkg.applicationInfo.processName,  
                    s.info.processName, pkg.applicationInfo.uid);  
                mServices.addService(s);  

                ......  
            }  

            N = pkg.receivers.size();  
            r = null;  
            for (i=0; i<N; i++) {  
                PackageParser.Activity a = pkg.receivers.get(i);  
                a.info.processName = fixProcessName(pkg.applicationInfo.processName,  
                    a.info.processName, pkg.applicationInfo.uid);  
                mReceivers.addActivity(a, "receiver");  

                ......  
            }  

            N = pkg.activities.size();  
            for (i=0; i<N; i++) {  
                PackageParser.Activity a = pkg.activities.get(i);  
                a.info.processName = fixProcessName(pkg.applicationInfo.processName,  
                    a.info.processName, pkg.applicationInfo.uid);  
                mActivities.addActivity(a, "activity");  

                ......  
            }  

            ......  
        }  

        ......  

        return pkg;  
    }  

    ......  
}  

这个函数主要就是把前面解析应用程序得到的package、provider、service、receiver和activity等信息保存在PackageManagerService服务中了。

PackageManagerService的作用总结:

1)从apk, xml中载入pacakge信息, 存储到内部成员变量中, 用于后面的查找. 关键的方法是scanPackageLI().
2)各种查询操作, 包括query Intent操作.
3)install package和delete package的操作. 还有后面的关键方法是installPackageLI().

后面重点介绍installPackageLI,后面的额方式本质都会调用它。

接着看下一篇

方法最后我们可以看到再次调用安装接口完成安装。

对于mSetting的介绍还不完善,后续会继续补充

本文是读过下面的几篇博客和Android系统源代码情景分析之后写成的,感谢各位作者。

参考:

http://ticktick.blog.51cto.com/823160/1669525
http://blog.csdn.net/hdhd588/article/details/6739281
http://blog.csdn.net/luoshengyang/article/details/6766010
《Android系统源代码情景分析》

点击查看更多内容
9人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
424
获赞与收藏
5663

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消