[Android learning] apk generation and installation

1. Concept

1) Android's package file APK is divided into two parts: code and resources, so packaging is also divided into resource packaging and code packaging.

2. Packaging process

Packaging process
1) Package resource files (including AndroidManifest.xml, layout files, various xml resources, etc.) through the AAPT tool to generate R.java files.
2) Process AIDL files through AIDL tools to generate corresponding Java files.
3) Compile the project source code through the Javac tool to generate the Class file.
4) Convert all Class files into DEX files through the DX tool. This process mainly completes the conversion of Java bytecodes into Dalvik bytecodes, compression of constant pools, and removal of redundant information.
5) Package resource files and DEX files to generate APK files through the ApkBuilder tool.
6) Use KeyStore to sign the generated APK file.
7) If it is the official version of the APK, the ZipAlign tool will also be used for alignment processing. The alignment process is to offset the starting distance of all resource files in the APK file by an integer multiple of 4 bytes, so that through memory mapping Accessing APK files will be faster.

3. APK installation process

apk installation process
1) Copy the APK to the /data/app directory, unzip and scan the installation package.
2) The resource manager parses the resource files in the APK.
3) Parse the AndroidManifest file and create the corresponding application data directory in the /data/data/ directory.
4) Then optimize the dex file and save it in the dalvik-cache directory.
5) Register the information of the four major components parsed by the AndroidManifest file into the PackageManagerService.
6) After the installation is complete, send the broadcast.

4. App startup process

After clicking the application icon, it will start the LauncherActivity of the application. If the process where LancerActivity is located is not created, a new process will be created. The overall process is the startup process of an Activity.
app startup process

1) Main characters

①Instrumentation
monitors the interaction between the application and the system.
②The AMS
component manages the dispatch center, which does nothing but manages everything.
③ActivityStarter
Activity startup controller, handles the influence of Intent and Flag on Activity startup, specifically:
1 Find the Activity that meets the startup conditions, if there are more than one, let the user choose;
2 Verify the validity of the startup parameters;
3 Return The int parameter represents whether the Activity was started successfully.

The role of the ActivityStackSupervisior class can be seen from its name. It is used to manage the task stack.
This is a class only available in the high-level version. It is used to manage multiple ActivityStacks. In the earlier version, there was only one ActivityStack corresponding to the mobile phone screen. Later, after the high-level version supported multiple screens, there were multiple ActivityStacks, so ActivityStackSupervisior was introduced to use it. Manage multiple ActivityStacks.
⑤ActivityStack is
used to manage the activities in the task stack.

ActivityThread is the inner class of ActivityThread, and the startup, switching, scheduling and other operations of Activity, Service, BroadcastReceiver are all completed in this class.

2) Related processes

① caller process

If the application is started on the desktop, it is the Launcher application process.

②System Server process where ActivityManagerService, etc. are located

This process mainly runs system service components.

③Zygote process

This process is mainly used to fork new processes.

④The newly started application process

This process is the process used to carry the application running, and it is also the main thread of the application (the newly created process is the main thread), which handles the life cycle of components, interface drawing and other related things.

3) The whole process

①Click the desktop application icon, and the Launcher process sends the request to start the Activity (MainActivity) to the AMS in the form of Binder.
②After AMS receives the startup request, it delivers ActivityStarter to process information such as Intent and Flag, and then hand it over to ActivityStackSupervisior/ActivityStack ③Processing the
related process of Activity stacking. At the same time, request the Zygote process to fork a new process in Socket mode.
Zygote forks a new process after receiving the new process creation request.
④Create an ActivityThread object in the new process. The newly created process is the main thread of the application. Open the Looper message loop in the main thread and start processing the creation of Activity.
⑤ActivityThread uses ClassLoader to load Activity, create Activity instance, and call back Activity's onCreate() method. This completes the startup of the Activity.

5, class loader

1)PathClassLoader

Only the APK files that have been installed in the Android system can be loaded, that is, the /data/app directory, the default class loader of Android.

2)DexClassLoader

It can load dex, jar, apk, zip files in any directory.

6, 64k method

1) Problem

With the increase of functions, the number of methods increases, and the so-called 64k method number problem occurs.

2) Cause

The Android APK file is essentially a compressed file. The classes.dex file it contains is a Dalvik bytecode file, and the compiled Java code is stored in this dex file. The Dalvik executable specification limits the maximum number of methods a single .dex file can reference to 65536.

In the DEX file, the number of methods, fields, classes, etc. is indexed using the short type, that is, two bytes (65535), and methods, fields, classes, etc. have this limitation.

During the installation process of the APK, dexopt will be called to optimize the DEX file into an ODEX file. dexopt uses LinearAlloc to store application information. Regarding the size of the LinearAlloc buffer, different versions have experienced the limit of 4M/8M/16M. When the buffer is exceeded, it will be thrown. Out INSTALL_FAILED_DEXOPT error.

3) Solution – Use of MultiDex

In order to avoid the above problems, google launched the MultiDex solution to solve the problem of the number of methods exceeding the limit, and can configure applications with more than 64K methods.

4) Solution principle

① Before Android
5.0, before Dalvik 5.0, only one classes.dex was generated for each APK, so there would be the problem that the number of methods mentioned above exceeds the limit. If we can divide a dex file into multiple, when the application starts, Load the first (main dex) dex file, and when it starts, load the other dex files in turn. In this way, the above problems can be avoided. MultiDex implements such a function.
② After Android 5.0, Android 5.0
and later versions use the ART runtime mechanism that supports loading multiple dex files from apk. When the application is installed, load the classed(…N).dex file and Compiled into a .oat file to support running on Android devices.

5) Realize

Configure build.gradle

android {
      compileSdkVersion 21
      buildToolsVersion "21.1.0"//必须使用21或之后的版本
      defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...


        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
  }
  dependencies {
  compile 'com.android.support:multidex:1.0.0'
  }

Configure Application
If the user does not override the Application, just modify the content in the Manifest file:

<application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>

If the user inherits and overrides the Application, you can replace the inherited Application with MultiDexApplication.
Or override the attachBaseContext() method,

@Override
 protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
}

Pay special attention, if this part of the code is not implemented, a NoClassDefFoundError error will occur at runtime, especially when relying on the third-party function library.
This problem has appeared many times before, when it was caused by configuring the build.gradle file but not using the MultiDexApplication. So developers must remember to use MultiDexApplication or MultiDex.install(this), refer to the configuration Application mentioned above.

There is another situation, as mentioned above, when using the MultiDex mechanism, there must be a master dex file and a slave dex file. The classes required when the application starts should be placed in the master dex, otherwise NoClassDefFoundError will occur. In this case, you can manually add some classes to the main dex:

multiDexKeepFile
manually adds the class to be placed in Main.dex.

android/support/multidex/MultiDex.class

multiDexKeepProguard
manually adds the classes to be placed in Main.dex in the way of Proguard.

-keep class android.support.multidex.** {
    *;
}

Then configure in build.gradle:

android {
    defaultConfig {
        multiDexEnabled true
        multiDexKeepProguard file('multiDexKeep.pro') 
        multiDexKeepFile file('multiDexKeep.txt') 
    }
}
dependencies {
    compile'com.android.support:multidex:1.0.1'
}

6) Multidex optimization

Multidex increases the time to build your application, a necessary process that can slow down your development progress. To speed up the build process, we can configure productFlavors in Gradle.
When developing, change minSdkVersion to 21 to use the ART runtime mechanism, which can speed up the build. Change to the appropriate minSdkVersion during release, which only takes a long time during release.
The build.gradle configuration is as follows:

android {
        productFlavors {
            dev {
                minSdkVersion 21
            }
            prod {
                minSdkVersion 14
            }
        }
              ...
        buildTypes {
            release {
             ...
            }
        }
    }
    dependencies {
      compile 'com.android.support:multidex:1.0.0'
    }

After completing the above configuration, you can use the devDebug variant app that combines the dev productFlavor and buildType properties.
This variant app includes the following features:

Disabled obfuscation (proguard)
support multidex
minSdkVersion is set to Android API level 21.
It is worth noting that the devDebug variant app with the above configuration can only run on Android 5.0 devices.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325540617&siteId=291194637