Android Dexclassloader Dynamic Loading technology detailed

Source: Internet
Author: User

Introduce the project to a certain large time will find that the number of methods too many, installation package is not loaded up, this is not surprising, we all know when the number of methodsover 65536When this number is limited, Block in the 2.x system above will be unable to install the situation, this time the dynamic loading technology is not important, our project in order to be compatible with 2.x mobile phone is also used in Android dynamic loading technology, here I will explain in detail how to use, how to combat, I feel, empty talk theory is not as good as hands. ExampleThe following is an example of how to implement dynamic loading, using different methods to invoke. preparatory work1: Create a new Java project (I'm lazy I'll just build a new Android project) 2: Then look at the package path. We typed the code inside: first Iinterface.java
Package com.demo.dex;/** * External interface *  * @author Edsheng *  */public interface IInterface {public void call ();p ublic Str ing GetData ();}

And then the Iclass.java.
Package Com.demo.dex;import Android.content.context;import Android.widget.toast;public class IClass implements IInterface {private Context context;public IClass (context context) {super (); this.context = context;} @Overridepublic void Call () {Toast.maketext (context, "call method", 0). Show (); @Overridepublic String GetData () {return "hello,i am from IClass";}}
Notice the implementation class above, I passed it to the context object at the time of construction, why should I do this? Is there anything in Android that gets through the context? I'm only going to call a toast here for experimentation.now that the preparation is ready, let's start with the next step. Exported as a jar. Project Right-click, export->java->jar file selected SRC below the two classes on the line.
Export our jar file I named him Test.jar and then convert the Java class file to the bytecode that Android recognizes. Using the DX tool, you can search for this tool under the Andorid SKD directory, previously said in Platform-tools this directory but I did not find, on the contrary, I found in the Build-tools subdirectory inside the different versions of the DX tool, I randomly searched for a version of 19.0.3 and then copied the Test.jar to this directory, and typed it in the cmd command .
DX--dex--output=testdex.jar Test.jar

then the preparation is done, so an optimized jar, or DEX, is ready. official Start then post the code for Fileutil.java
package Com.demo.utile;import Java.io.file;import Java.io.fileoutputstream;import Java.io.inputstream;import Android.content.context;import Android.os.environment;public class Fileutile {public static void Copyassertjartofile ( Context context, String filename,string des) {try {File file = new file (Environment.getexternalstoragedirectory (). ToString () + File.separator + des); if (File.exists ()) {return;} InputStream InputStream = Context.getassets (). open (filename); File.createnewfile (); FileOutputStream FileOutputStream = new FileOutputStream (file), byte buffer[] = new Byte[1024];int len = 0;while (len = in Putstream.read (buffer))! = 0) {fileoutputstream.write (buffer, 0, Len);} Fileoutputstream.close (); Fileoutputstream.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} 
The main function of this class is to extract our jar equivalent to a directory. I am here to extract to the external device in fact, the security is not high, but in order to facilitate my doing so, it is recommended to extract the package under the directory. Remember, don't forget to add permissions to your APP!!!!! File read and Write permission!!!Finally, let's look at the code inside the activity.
Package Com.demo.activity;import Java.io.file;import Java.lang.reflect.constructor;import Java.lang.reflect.Method ; Import Android.app.activity;import Android.content.context;import android.os.bundle;import android.os.Environment Import Com.demo.utile.fileutile;import Dalvik.system.dexclassloader;public class Mainactivity extends Activity {@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Fileutile.copyassertjartofile (This, "Testdex.jar", "Testdex.jar"); File File = new file (Environment.getexternalstoragedirectory (). toString () + File.separator + "Testdex.jar"); final file Optimizeddexoutputpath = Getdir ("temp", context.mode_private);D exclassloader classLoader = new Dexclassloader ( File.getabsolutepath (), Optimizeddexoutputpath.getabsolutepath (), Null,getclassloader ()); try {Class<?> IClass = Classloader.loadclass ("Com.demo.dex.IClass"); constructor<?> istructor = Iclass.getconstructor (Context.class);//Using the reflection principle to invoke Method method = Iclass.getmethod ("call", null); String data = (string) Method.invoke (Istructor.newinstance (this), NULL); SYSTEM.OUT.PRINTLN (data);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
In fact, this call has a point to note is that I feel like this every time to call the reflection, always feel that I am not very friendly, then here I have given the following a way of writing, the most important place is to get iinterface this interface, Copy the Iinterface.java file into your project and remember that the package name is the same, and we can call it when we call it.
class<?> IClass = Classloader.loadclass ("Com.demo.dex.IClass"); constructor<?> istructor = Iclass.getconstructor (context.class); IInterface iinterface = (Iinterface) Istructor.newinstance (this); String data = Iinterface.getdata (); Iinterface.call (); Toast.maketext (this, data, 0). Show ();
Does it look more comfortable?Well, share it here today. Demo:csdn upload convulsions, here first on to Baidu network disk click here

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.