Android Dynamic load byte code

Source: Internet
Author: User

Overview

In the face of frequent changes to the app business logic, if every change is made to an app that upgrades the app's user experience, then the app's modular upgrade (here, unlike the incremental upgrade) is a good solution, Let the user change the business logic in the app without feeling completely. To implement this modular upgrade, the dynamic loading of bytecode (Jar/dex) is the theoretical basis for achieving this requirement.

android System load byte code

The Android virtual machine (Dalvik VM) does not recognize the bytecode in the normal jar, so a byte-code conversion tool is required to convert the jar to all the bytecode in the Dex,jar package, and the Classes.dex will be entered. Such bytecode can be recognized by the Dalvik virtual machine.

Example Explanation

source code Download , need to prepare two works, an Android project (Androidpractice), Android project to go to load bytecode. Ning outside a common Java project (dexmodule), look at the engineering structure below. It is important to note that the Idynamicload interface is required in both projects, and the package name is the same.

Bytecode loading engineering structure

Dexmodule Engineering Explanation

Dexmodule this project only two classes, one is the interface idynamicload, this interface is the article began to mention the module upgrade key, only need to pre-contract the interface, the interface is published to the caller, the specific implementation of the caller is completely transparent, This can be done at random to change the implementation of the interface, Ning one is the implementation of the interface class Dynamicload. The implementation is very simple to return a string.

Package Com.vjson.module;public interface Idynamicload {public    String dexload ();}

<span style= "Font-weight:normal;" >package Com.vjson.module;public class Dynamicload implements Idynamicload {    @Override public    String Dexload () {        return "dexload practice";    }} </span>

Export Jar Package

When exporting the jar package, it is important to note that do not export idynamicload This interface file, because the Android project already has an interface file, otherwise loading bytecode will cause bytecode conflict.

Export JAR Package

byte-code conversion

Using the bytecode conversion tool mentioned earlier, convert the jar to Dex known to the Dalvik VM. d2j-jar2dex.sh The-o parameter of this command specifies the output file.

D2j-jar2dex.sh-o Module.jar Dynamicload.jar

The resulting module.jar is then placed inside the sdcard of the phone.

ADB push module.jar/mnt/sdcard/

Load Dex

Loading bytecode requires the Dexclassloader class, which is responsible for extracting (a process of extracting) Classes.dex from the jar package and loading the bytecode into memory, then loading the required classes through the LoadClass method, looking at the detailed code below, Note the highlighted line.

Package Com.vjson.practice;import Java.io.file;import Android.annotation.targetapi;import android.app.Activity; Import Android.os.build;import android.os.bundle;import Android.os.environment;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;import Com.vjson.dynamicload.r;import Com.vjson.module.idynamicload;import Dalvik.system.dexclassloader;public Class    Mainactivity extends Activity {private Button mBtn;    Private Idynamicload mdynamicload; @TargetApi (build.version_codes. Ice_cream_sandwich) public static final Idynamicload Loadbytecode () {File Jarfile = new File (environment.getext        Ernalstoragedirectory (). toString () + File.separator + "Module.jar");        File Optmizedpath = BaseApplication.sInstance.getDir ("dex", mode_private);                 Dexclassloader loader = new Dexclassloader (Jarfile.getabsolutepath (), Optmizedpath.getabsolutepath (), NULL, Baseapplication.sinstancE.getclassloader ());        Idynamicload dynaicload = null;            try {class<?> clazz = Loader.loadclass ("Com.vjson.module.DynamicLoad");        Dynaicload = (idynamicload) clazz.newinstance ();        } catch (ClassNotFoundException e) {e.printstacktrace ();        } catch (Instantiationexception e) {e.printstacktrace ();        } catch (Illegalaccessexception e) {e.printstacktrace ();    } return dynaicload;        } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mdynamicload = Loadbytecode ();        MBtn = (Button) Findviewbyid (R.ID.BTN);                Mbtn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {                String str = mdynamicload.dexload ();            Toast.maketext (Getapplicationcontext (), str, toast.length_short). Show ();  }      }); }}

Note the code of 26 lines, through the context of the Getdir ("Dex", Mode_private) method to obtain the application's private directory, which is due to security reasons from the beginning of Android4.1.2, preventing code injection attacks , the bytes must be stacked into a private directory under the data/data/application package name/. The Classes.dex from the jar package is placed under this directory.

Summary

This article mainly introduces, the Android bytecode loading technology, for the next article Android Modular upgrade provides a theoretical basis, in fact, the most important thing is to define the interface, through the interface call and the implementation end of the communication. The integrity validation and security validation of the jar package will be explained in the modular upgrade.

Android Dynamic load byte code

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.