Android Application Management Mechanism

Source: Internet
Author: User

Android Application Management is mainly managed by the packagemanager class. contextimpl. Java is the abstract class of packagemanager. In contextimpl. Java, an internal static class is applicationpackagemanager, which implements all the interfaces of packagemanager.

 static final class ApplicationPackageManager extends PackageManager {..........}

Applicationpackagemanager is implemented by encapsulating AND calling ipackagemanager.

 public PackageInfo getPackageInfo(String packageName, int flags)                throws NameNotFoundException {            try {                PackageInfo pi = mPM.getPackageInfo(packageName, flags);                if (pi != null) {                    return pi;                }            } catch (RemoteException e) {                throw new RuntimeException("Package manager has died", e);            }            throw new NameNotFoundException(packageName);        }

Here, mpm is ipackagemanager, and packagemanagerservice is the implementation of ipackagemanager. Therefore, the call to packagemanager is implemented in packagemanagerservice. java. The implementation of each method in packagemanagerservice. java.

Packagemanagerservice startup process:

Packagemanagerservice (context, factorytest) is the main process of the package management service. It completes parsing the APK files under/system/APP,/data/APP,/system/framework,/data/APP-Private. The detailed process is as follows:

1. Establish a socket connection between the Java-layer installer and the installd on the C-layer, so that functions such as install, remove, and dexopt on the upper layer are ultimately implemented by installd at the bottom layer.

2. Establish a packagehandler message loop to process external APK installation request messages, such as ADB install. When packageinstaller installs the APK, a message is sent.

3. parse XML files (Framework/base/data/etc/) under/system/etc/permission, including platform. xml and feature of various hardware modules supported by the system. The main work is as follows:

(1) establishes a ing between the underlying user IDs and group IDs. You can specify a permission that corresponds to several group IDs. When an APK is granted this permission, it also belongs to these groups.

(2) Assign permissions to some underlying users, for example, assign various permission permissions to shell, and assign a permission to a uid. When a process uses this UID to run, it has this permission.

(3) Library. Some Applications added by the system must be linked to the extended jar library;

(4) feature: each time a hardware is added to the system, the corresponding feature must be added. put the parsing result in msystempermissions, msharedlibraries, and msettings. mpermissions, mavailablefeatures, and other sets are used for system query and permission configuration.

4. Check whether/data/system/packages. xml exists. This file is generated

Created by writelp (), which records the permissions of the system and the name, codepath, flags, version, uesrid, and other information of each APK.

Androidmanifest. XML is obtained through parsing. After the APK is parsed, the updated information is written to this file and maintained

Save it to flash, and then read the relevant information from it and add it to the memory list. When there is an APK

Upgrade. This file is updated during installation or deletion.

5. Check the jar files in bootclasspath, msharedlibraries, And/system/framework.

Whether dexopt is required. If so, dexopt is used for optimization.

6. Start appdirobserver thread monitoring/system/framework,/system/APP,/data/APP,/data/

App-Private directory events, mainly listening for add and remove events. For the underlying directory listening

Inotify is a file system change notification mechanism, such as file addition and deletion.

Such events can immediately let the user State know, it provides powerful support for user State monitoring file system changes.

Scanpackageli (file, Int, INT) is called when an add event exists;

Call removepackageli () for processing when a remove event exists;

7. parse the APK files in the preceding directories one by one, mainly to parse the androidma-

The nifest. xml file processes resource files such as asset and res, and establishes configuration structure information for each APK,

Add the configuration information of each APK to the global list for management. F

8. Save the parsed APK information to the packages. xml and packages. List Files,

Packages. xml records the following data: pkgname, userid, debugflag, and datapath (package data path)

Dexopt:

If we want to further improve the runtime performance, we still need to further optimize the DEX file. Optimize Dex to generate a classes that can be quickly loaded and executed. the Dex file includes byte-swapping, structure realigning, and basic structure checks to update the odex header. To ensure the correctness of the odex process, Android provides a dexopt tool, this tool is used as an auxiliary tool for virtual machines. When the system is started, the Dalvik virtual machine performs a better operation on the DEX file imported by the kernel.
 

There are two timing for optimization:

For preset applications, an optimization file can be generated after the system compilation, ending with odex. In this way

In addition to the APK file (excluding Dex), there is a corresponding odex file;
For non-preset applications, Dex files included in the APK file will be optimized through dexopt at runtime, and the optimized files will be saved in the cache (data/Dalvik-Cache ).

Android Security Mechanism Overview:

Android is a permission separation system, which uses the existing permission management mechanism in Linux to assign different UID and GID to each application, thus, the private data and access (native and Java layers use this sandbox mechanism) between different applications are isolated. At the same time, Android also expands on this basis and provides the permission mechanism, which is mainly used to subdivide permissions and control access to certain specific operations that can be executed by the application, the per-Uri permission mechanism is also provided to provide access to certain data blocks.
Application-level security control is implemented through user ID and group ID; component-level permission is used to restrict access to a certain component; and permission-based per URI is used for security control at the data level.

Uid gid gids:

Android permission separation is based on the existing uid, GID, and gids in Linux.
UID: when Android installs an application, it will be assigned a uid. The UID of a common android application is allocated from 10000 (process. first_application_uid), and the UID of the system process is smaller than 10000.
GID: for common applications, GID is equal to uid. Because the UID and gid of each application are different, both the native layer and the Java layer can protect private data.
Gids: gids are generated by the framework during application installation and related to the specific permissions applied by the application. If the permission applied by the application is granted and there is a corresponding gids, The gids of this application will contain this gids.

Installer class:

In the constructor, initialization of some member variables is performed first, such as mcontext, mfactorytest, mmetrics, and msettings.
The most important thing is to initialize the minstaller variable:

  Installer installer = new Installer();        if (installer.ping() && Process.supportsProcesses()) {            mInstaller = installer;        } else {            mInstaller = null;        }

Installer is a tool class used to communicate with the underlying C Module of packagemanager. It communicates with socket. All packagemanager operations such as APK installation and uninstallation are performed through installer. To call the installer, Ping () is first called to determine whether the socket is connected.

Connection Method: CONNECT:

 private boolean connect() {        if (mSocket != null) {            return true;        }        Slog.i(TAG, "connecting...");        try {            mSocket = new LocalSocket();            LocalSocketAddress address = new LocalSocketAddress(                "installd", LocalSocketAddress.Namespace.RESERVED);            mSocket.connect(address);            mIn = mSocket.getInputStream();            mOut = mSocket.getOutputStream();        } catch (IOException ex) {            disconnect();            return false;        }        return true;    }

Transaction first checks the connection. If the socket connection is normal, it writes the CMD command to the socket file, receives the returned information, and returns it to execute:

private synchronized String transaction(String cmd) {        if (!connect()) {            Slog.e(TAG, "connection failed");            return "-1";        }        if (!writeCommand(cmd)) {                /* If installd died and restarted in the background                 * (unlikely but possible) we'll fail on the next                 * write (this one).  Try to reconnect and write                 * the command one more time before giving up.                 */            Slog.e(TAG, "write command failed? reconnect!");            if (!connect() || !writeCommand(cmd)) {                return "-1";            }        }//        Slog.i(TAG,"send: '"+cmd+"'");        if (readReply()) {            String s = new String(buf, 0, buflen);//            Slog.i(TAG,"recv: '"+s+"'");            return s;        } else {//            Slog.i(TAG,"fail");            return "-1";        }    }

Execute (string cmd ):

 

  private int execute(String cmd) {        String res = transaction(cmd);        try {            return Integer.parseInt(res);        } catch (NumberFormatException ex) {            return -1;        }    }

Install () method:

    public int install(String name, int uid, int gid) {        StringBuilder builder = new StringBuilder("install");        builder.append(' ');        builder.append(name);        builder.append(' ');        builder.append(uid);        builder.append(' ');        builder.append(gid);        return execute(builder.toString());    }

Other methods:

(1) dexopt (string apkpath, int uid, Boolean ispublic); optimize Dex files
(2) movedex (string srcpath, string dstpath); move the DEX File
(3) rmdex (string codepath); Delete the DEX File
(4) Remove (string name); Delete APK
(5) Rename (string oldname, string newname); rename
(6) deletecachefiles (string name); Delete the cache file
(7) clearuserdata (string name); delete user data
(8) freecache (long freestoragesize); release cache space
(9) setforwardlockperm (string packagepathsuffix, int GID) adds a prefix to the APK File
(10) getsizeinfo (string pkgname, string apkpath, string fwdlockapkpath, packagestats pstats) Get APK Information
(11) movefiles (); move files.

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.