Packageinstaller Principles & packagemanagerservice & packageparser and androidmanifest. xml

Source: Internet
Author: User

Packageinstaller principles

 

Application installation is the main feature of a smart machine. Users can install various applications (such as games) on their mobile phones and perform management operations such as uninstallation. APK is the abbreviation of Android package, that is, the android installation package. APK is a file format similar to Symbian sis Or sisx. Directly upload the APK file to the android simulator or Android mobile phone for installation.

Android applications can be installed in the following four ways:
1. system application installation-completed at startup, no installation Interface
2. download and install the application over the Internet-the application is completed through the market application, and there is no installation Interface
3. Install the ADB tool-no installation interface.
4. The third party shall install zookeeper through the SDK-based APK file. The packageinstaller.apk application shall process the installation and uninstallation interfaces.
Application installation process and Path
Application installation involves the following directories:
Application of the System/APP systemProgram, Cannot be deleted
The directory where data/app user programs are installed. You have the permission to delete them.
Copy the APK file to this directory during installation
Data/data stores Application Data
Data/Dalvik-Cache: Install the DEX file in the apk to the Dalvik-cache directory (the DEX file is the executable file of the Dalvik virtual machine, and its size is about 1/4 of the size of the original APK file)

Installation Process: copy the APK installation package to the data/APP directory, decompress and scan the installation package, and save the DEX file (Dalvik bytecode) to the Dalvik-cache directory, and create the corresponding application data directory under the Data/data directory.
Uninstall process: delete the files and directories created under the preceding three directories during installation.
 

1. system application installation:
The packagemanager service processes the installation, uninstallation, and management of various applications. during startup, The systemserver starts the service.
(Source file path: Android/frameworks/base/services/Java/COM/Android/Server/packagemanagerservice. Java)

 
Packagemanager service start process:
1. First scan and install the jar package under the "System/framework" Directory
1. scandirli (mframeworkdir, packageparser. parse_is_system,
Scanmode | scan_no_dex );

 
2. Step 2 scan and install various system applications under the "System/APP" Directory
Scandirli (msystemappdir, packageparser. parse_is_system, scanmode );
 
3. Step 3 scan the "Data/APP" directory, that is, third-party applications installed by the user
Scandirli (mappinstalldir, 0, scanmode );
 
4. Step 4 scan the "Data/APP-private" directory, that is, installing the DRM-protected APK file (no such application has been encountered currently ).
Scandirli (mdrmappprivateinstalldir, 0, scanmode | scan_forward_locked );

Application Installation Process
1. scandirli (File Dir, int flags, int scanmode) traverses the files installed in the specified directory

2. scanpackageli (File scanfile,
File destcodefile, file destresourcefile, int parseflags,
Int scanmode) install the package file

3. scanpackageli (
File scanfile, file destcodefile, file destresourcefile,
Packageparser. Package PKG, int parseflags, int scanmode)
Obtain the information structure of the installation package by parsing the installation package parsepackage

4. minstaller. Install (pkgname, PKG. applicationinfo. uid,
PKG. applicationinfo. UID); implements the installation process of File Replication
(Source file path: Frameworks/base/cmds/installd. Install)

2. download the application from the market:
Google market applications can be used only after logon using a Gmail account. After selecting an application, download the installation package. During this process, a progress bar is displayed in the signal area of the mobile phone. After the download is complete, the packagemanager interface is automatically called for installation. The called interface is as follows:
Public void installpackage (final URI packageuri, final ipackageinstallobserver observer, final int flags)
Final URI packageuri: The Path saved after the file is downloaded.
Final ipackageinstallobserver observer: process the returned installation result
Final int flags: the installation parameter for the Application downloaded from the market. The installation parameter is-R (replace)
Installation Process of installpackage interface functions:
1. Public void installpackage (
Final URI packageuri, final ipackageinstallobserver observer, final int flags,
Final string installerpackagename)
Final string installerpackagename: After the installation is complete, the name is stored in settings. Generally, it is null, not a key parameter.
2. File tmppackagefile = copytempinstallfile (packageuri, Res );
Copy the APK file to a temporary file in the temporary directory
3. Private void installpackageli (URI ppackageuri,
Int pflags, Boolean newinstall, string installerpackagename,
File tmppackagefile, packageinstalledinfo res)
Parse the temporary file and obtain the application package name pkgname = packageparser. parsepackagename (
Tmppackagefile. getabsolutepath (), 0 );
4. Determine if the install_replace_existing parameter is included, call replacepackageli (pkgname,
Tmppackagefile,
Destfilepath, destpackagefile, destresourcefile,
PKG, forwardlocked, newinstall, installerpackagename,
Res)
5. If not, call installnewpackageli (pkgname,
Tmppackagefile,
Destfilepath, destpackagefile, destresourcefile,
PKG, forwardlocked, newinstall, installerpackagename,
Res );
6. Private packageparser. Package scanpackageli (
File scanfile, file destcodefile, file destresourcefile,
Packageparser. Package PKG, int parseflags, int scanmode)
The process after scanpackageli is the same as that after the application is started.
3. Install from ADB
Android debug bridge (ADB) is a tool that comes with the SDK to manage devices. You can use the ADB command line to install applications on mobile phones or simulators. The source file of the function is pm. java.
(Source file path: Android/frameworks/base/cmds/PM/src/COM/Android/commands/PM. Java)
The ADB command line is in the form of ADB install <path_to_apk>. It can also contain installation parameters such as "-l" "-R" "-I" "-t"
Judge parameters in the runinstall () function
"-L"-install_forward_lock
"-R" -- install_replace_existing
"-I" -- installerpackagename
"-T" -- install_allow_test
Our commonly used parameter is-R, which indicates that the application with the same name already installed on the mobile phone is overwritten. Applications downloaded from the market are also directly input to install this parameter.
Runinstall and market call the same interface to install the application.
Public void installpackage (android.net. Uri packageuri, Android. content. PM. ipackageinstallobserver observer, int flags, java. Lang. String installerpackagename)
4. Third-party application installation-install the SDK through the APK file in the SD card
The supervisor processes the installation and uninstallation interfaces in this mode, such:

Packageinstalleractivity parses the package and determines whether the APK file is available.
Create a temporary installation file/data/COM. Android. packageinstaller/files/apidemos.apk
Start the installation confirmation interface startinstallconfirm to list the basic information of the parsed application. If an application with the same name has been installed on your mobile phone, you need to confirm whether to replace and install the application.
After confirming the installation, start installappprogress and call the installation interface to complete the installation.
PM. installpackage (mpackageuri, observer, installflags );
Others:
1. The internal class appdirobserver of packagemanagerservice. Java implements the function of listening to the app Directory: when you drag an APK to the app directory, you can directly call scanpackageli to complete the installation.
2. The "Data/system/packages. xml" file in the mobile phone data area contains the basic information of all installed applications on the mobile phone, such as the installation path and applied permission.

 

------------------------------------------------------ Gorgeous split line ---------------------------------------------------------------

Packagemanagerservice Annotation

 

Packagemanagerservice methods can be roughly divided into the following types,
1) load the pacakge information from APK and XML and store the information to the internal member variables for later search. The key method is scanpackageli ().
2) Various query operations, including query intent operations.
3) install package and delete package. The key method is installpackageli ().
4) Other operations, including permission, signature, and freestorage.

First, let's take a look at several important support classes used by pacakgemanagerservice, and then list several key internal data member variables of packagemanagerservice. Finally, we will note several key processes.

Packagemanagerservice uses several important support classes:

Packageparser. This class is mainly used to parse the APK and analyze its androidmanifest. XML to get various package information.ArticleThis will not be repeated. The special packageparser. Package class is used to hold the parsed information.

Packagemanagerservice. settings, used to hold the currently valid package information. It is dynamic. for example, user ID, Login User, permission, signature, and origpackage (mrenamedpackages) information. the so-called install package includes extracting information from the package to be installed and updating packagemanagerservice. content in settings. in particular, settings takes special care of login user and origpackage. in addition, to accelerate the startup speed, the settings content is written to/data/system/packages. XML, packages-backup.xml, and packages. list, which will be directly loaded at next startup.

Installer. This class assists in the installation process. More operations on files/paths are implemented in C/CPP. the real work is undertaken by installd. installer only connects to installd through named socket "installd" and uses the simple cmd-respond protocol to command installd to complete the work. in its 'install' command, we can see that it only creates the/data/<pkgname> directory.

Key member variables in packagemanagerservice:

// (Pkgname => package), package is the one installed.

Final hashmap <string, packageparser. Package> mpackages =

New hashmap <string, packageparser. Package> ();

// Current package settings info, such as userid, origpackage

//, Restore user, permission, signature, etc

Final settings msettings;

// (System uid => permission), permissions read from/system/etc/permissions/<files> are stored here.

// Especially/system/etc/permissions/platform. xml

Final sparsearray

New sparsearray

// (Pkgname => sharedlib), corresponding to <library> tag

Final hashmap <string, string> msharedlibraries =

New hashmap <string, string> ();

// All available activities, for resolving intent

Final activityintentresolver mactivities =

New activityintentresolver ();

// All available receivers, for resolving intent

Final activityintentresolver mreceivers =

New activityintentresolver ();

// All available services, for resolving intent

Final serviceintentresolver mservices =

New serviceintentresolver ();

Several key processes,

Initialization Process
--------------

Packagemanagerservice is created by systemserver by calling Main after activitymanagerservice is created. It is a single instance.

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

In the constructor, packagemanagerservice performs these tasks,

1) Start Your Own handlerthread to generate your own mhandler.
2) read systempermissions from all XML files in/system/etc/permissions/, especially platform. xml. These are the default permission configurations of the system.
3) scan/system/framework/,/system/APP/,/data/APP/, And/data/APP-private/to collect various package information, update to the internal member variable. these will be used when packagemanagerservice executes various functions. especially query intent.

More detailed notes,
Packagemanagerservice
Mhandlerthread. Start ();

Mhandler = new packagehandler (mhandlerthread. getlooper ());

Readpermissions ();

Mrestoredsettings = msettings. readlp ();

--/System/framework/
Scandirli (mframeworkdir, packageparser. parse_is_system | packageparser. parse_is_system_dir, scanmode | scan_no_dex );

--/System/APP/
Scandirli (msystemappdir, packageparser. parse_is_system | packageparser. parse_is_system_dir, scanmode );

-- Prune any system packages that no longer exist.

-- Clean up any incomplete package Installations

-- Delete TMP files

--/Data/APP/
Scandirli (mappinstalldir, 0, scanmode );

--/Data/APP-private/
Scandirli (mdrmappprivateinstalldir, packageparser. parse_forward_lock, scanmode );

Msettings. writelp ();

Private packageparser. Package scanpackageli (File scanfile, int parseflags, int scanmode)
Packageparser pp = new packageparser (scanpath );

PKG = pp. parsepackage (scanfile, scanpath, metrics RICS, parseflags );

Collectcertificatesli (PP, PS, PKG, scanfile, parseflags)

Setapplicationinfopaths (PKG, codepath, respath );

Scanpackageli (PKG, parseflags, scanmode | scan_update_signature );
-- Set mandroidapplication and mresolveactivity to 'android' package

-- Check all shared libraries and map to their actual file path.

-- Check PKG. useslibraries are contained in msharedlibraries.

-- Fill in PKG. useslibraryfiles according to PKG. useslibraries and PKG. usesoptionallibraries

-- Check PKG. reqfeatures in mavailablefeatures

-- If not in msettings, create one between usersettings and insert into msettings.

-- Check and note if we are renaming from an original package name

Pkgsetting = msettings. getpackagelp (PKG, origpackage, realname, SUID, destcodefile, destresourcefile, PKG. applicationinfo. Flags, true, false );

Verifysignatureslp (pkgsetting, PKG );

-- Verify that this new package doesn' t have any content providers that conflict with existing packages.

-- Get Data dir. If not exists, install or create the data dir. If exists but uid not correct, reinstall.

-- Perform shared library installation and Dex validation and optimization, if this is not a system app.

-- Request the activitymanager to kill the process (only for existing packages)

Msettings. insertpackagesettinglp (pkgsetting, PKG); -- add the new setting to msettings

Mpackages. Put (PKG. applicationinfo. packagename, PKG );

-- Set mprovidersbycomponent and mproviders according to PKG. Providers

-- Set mservices according to PKG. Services

-- Set mreceivers according to PKG. Receivers

-- Set mactivites according to PKG. Activities

-- Set mpermissiongroups according to PKG. permissiongroups

-- Set msettings. mpermissiontrees or msettings. mpermissions according to PKG. Permissions

-- Set minstrumentation according to PKG. Instrumentation

-- Set mprotectedbroadcasts according to PKG. protectedbroadcasts

Install package process
--------------

The install package entry is installpackage (). install package is usually a time-consuming process, so the android handler mechanism is used.
First, the parameter is encapsulated into init_copy message and sent to handlerthread.
After handlerthread receives the message, it queues the parameters to mpendinginstils. Then, the mcs_bound process processes the queue and runs the installation.
The entire installation process of mcs_bound uses several installparams and installargs to pass the parameters and installation results. processpendinginstall () is finally called, and then the core installpackageli () of the install process is called ().
The complexity of installpackageli () is largely due to considerations of 1) new installation or upgrade, 2) origpackage

 

----------------------------------- Gorgeous split line --------------------------------------------------------------------

 

Notes on packageparser and androidmanifest. xml

 

Androidmanifest In the APK package. the XML file contains various descriptions of the package. packageparser analyzes and obtains the information. here is a brief description. first, we first list androidmanifest. the brief structure of the XML file, followed by the logic of packageparser.

Brief structure of androidmanifest. xml
==========================================
Androidmanifest. the XML content is defined in frameworks/base/CORE/RES/values/attrs_manifest.xml. here is a brief list. According to the layer-to-layer relationship, XML elements are marked in the form of "tagname, name". For some important attributes of XML elements, they are marked with "ATTR name.

Andridmanifest. xml
Manifest, androidmanifest
ATTR versioncode
ATTR versionname
ATTR shareduserid
ATTR shareduserlabel
ATTR installlocation

Permission, androidmanifestpermission
ATTR name, label, icon
ATTR permissiongroup
ATTR protectionlevel

Permission-group, androidmanifestpermissiongroup
ATTR name, label, icon

Permission-tree, androidmanifestpermissiontree
ATTR name, label, icon

Uses-SDK, androidmanifestusessdk

Uses-permission, androidmanifestusespermission
ATTR name

Uses-configuration, androidmanifestusesconfiguration
ATTR reqtouchscreen
ATTR requkeyboardtype
ATTR reqhardkeyboard
ATTR reqnavigation
ATTR reqfivewaynav

Application, androidmanifestapplication
ATTR name, label, icon
ATTR permission
ATTR Process
ATTR taskaffinity
ATTR persistent

Service, androidmanifestservice
ATTR name, label, icon
ATTR permission
ATTR Process
ATTR Enabled
ATTR exported

Receiver, androidmanifestreceiver
ATTR name, label, icon
ATTR permission
ATTR Process
ATTR Enabled
ATTR exported

Provider, androidmanifestprovider
ATTR name, label, icon
ATTR process, authorities, syncable
ATTR readpermission, writepermission, granturipermissions
ATTR permission
ATTR mulitprocess
ATTR Enabled
ATTR exported
Grant-Uri-permission, androidmanifestgranturipermission
ATTR path, pathprefix, pathpattern

Path-permission, androidmanifestpathpermission
ATTR path, pathprefix, pathpattern
ATTR permission, readpermission, writepermission

Activity, androidmanifestactivity
ATTR name, label, icon
ATTR theme, launchmode, screenorientation
ATTR configchanges, permission, Multiprocess
ATTR process, taskaffinity, allowtaskreparenting
ATTR finishontasklaunch, finishonclosesystemdialogs
ATTR cleartaskonlauch, nohistory
ATTR alwaysretaintaskstate, statenotneeded
ATTR excludefromrecents
ATTR enabled, exported
ATTR windowsoftinputmode

Activity-alias, androidmanifestactivityalias
ATTR name, label, icon
ATTR targetactivity
ATTR permission
ATTR enabled, exported

Uses-library, androidmanifestuseslibrary
ATTR name
ATTR required

Instrumentation, anroidmanifestinstrumentation
ATTR name, label, icon
ATTR targetpackage, handleprofiling
ATTR functionaltest

Uses-feature, androidmanifestusesfeature
ATTR glesversion
ATTR name
ATTR required

Supports-screens, androidmanifestsupportsscreens
ATTR smallscreens, normalscreens, largescreens
ATTR resizeable, anydensity

Protected-broadcast, androidmanifestprotectedbroadcast
ATTR name

Adopt-permissions, androidmanifestoriginalpackage
ATTR name

There are several special XML elements that can have multiple parent elements.
Application
Activity, Cycler, provider, Service
Permission, permissiongroup
Instrumentation
Meta-data, androidmanifestmetadata
ATTR name, value, Resource

Activity, Cycler, Service
Intent-filter, androidmanifestintentfilter
ATTR label, icon, priority

Action, androidmanifestaction
ATTR name

Data, androidmanifestdata
ATTR mimetype, scheme, host
ATTR port, path, pathprefix
ATTR pathpattern

Category, androidmanifestcategory
ATTR name

Intent, intent
ATTR action, Data, mimetype
ATTR targetpackage, targetclass

Category, intentcategory
ATTR name

Extra, extra
ATTR name, Value

Logic of packageparser
==========================================
The parsepackage () method of packageparser reads androidmanifest In the APK package. the XML file calls the *** XX () method of each sub-par to parse the package information. at the same time, packageparser defines some classes to accommodate the parsed information. the following figure shows the corresponding relationship.

Class XML elements
---------------------------------------------------
Package package
Permission permission, permission-tree
Permissiongroup permission-group
Activity activity, activity-alias, Cycler
Service
Provider provider
Instrumentation
Activityintentinfo intent-filter @ activity or Cycler
Serviceintentinfo intent-filter @ Service

The results of pacakgeparser are mainly used by packagemanagerservice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.