Android plugin dynamic loading jar

Source: Internet
Author: User

Sometimes you will see some applications corresponding to the folder in the SDcard ***.jar files, and now understand that these files are probably used for automatic Updates in the application.

Let's say, like Eclipse, you can install a variety of plugins by reserving the interface.

Android can also implement a similar business code update by dynamically loading the jar:(the jar described here is converted to Dalvik byte code via the DX tool, as described below)

Note: The first thing you need to know is that you can load dynamically in Android, but it's not as easy to load the jar dynamically as in Java.

Cause: Dalvik virtual machines Like other Java virtual machines, you first need to load the corresponding classes into memory as you run the program. In Java-standard virtual machines, class loading

Can be read from a class file, or it can be another form of binary stream, so we often use this to manually load the class while the program is running, thus achieving

The code dynamically loads the purpose of execution.
However, Dalvik virtual machines are not standard Java virtual machines, so they have the same place and are different in the class loading mechanism. We have to treat each other differently

The Android virtual machine (Dalvik VM) is a byte code that does not recognize the Java-typed jar and needs to be optimized for conversion to Dalvik byte code by using the DX tool. This point in

As we can see in our Android project's packaged apk, the introduction of the contents of the other jars is packaged into the classes.dex.

Focus:

The Dexclassloader class, which can load Jar/apk/dex, can also be loaded from an SD card.

Interface Class Idynamic

Implementing Class Dynamic (a class packaged into a jar)

The variable class is used to test whether an externally defined variable in this testvalue variable can be accessed in a jar.

Don't forget to add permissions in Androidmanifest.xml

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Start the code:

1.IDynamic

 Package com.example.test; Import Android.content.Context;  Public Interface idynamic {    // Reserved Interface method public    void  init (Context context );    }

2.Dynamic

 Packagecom.example.test;ImportAndroid.content.Context;ImportAndroid.widget.Toast;/*** Interface implementation class, which is the code packaged as a jar *@authorYema **/ Public classDynamicImplementsidynamic{@Override Public voidinit (Context context) {//TODO auto-generated Method StubToast.maketext (context, Constant.testvalue, Toast.length_long). Show (); }}

3.Variable

 Package com.example.test;  Public class Variable {            // variables to be tested public    static String TestValue = " 123456 ";}

4.MainActivity

 Packagecom.example.test;ImportJava.io.File;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.os.Environment;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.TextView;ImportDalvik.system.DexClassLoader; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Variable.testvalue= "heaven and earth heartless, with all things as a humble dog"; TextView Click=(TextView) Findviewbyid (R.id.click); Click.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubLoadClass (). Init (mainactivity. This);            }        }); }    /*** Load sdcard with directory Test.jar *@returnidynamic*/     Publicidynamic loadclass () {idynamic lib=NULL; String Dexpath= Environment.getexternalstoragedirectory (). toString () + File.separator + "Test.jar"; File Dexoutputdirs= This. Getapplicationcontext (). Getdir ("Dex", 0); /*** Dexpath The path of the APK or jar file that needs to be loaded. Contains multiple paths separated by File.pathseparator, on Android The default is ":" Optimizeddirectory optimized dex file storage directory, cannot be null LibraryPath target A list of C + + libraries used in the class, with each directory separated by File.pathseparator; can be null parent loader for the class loader, typically with the loader of the currently executing class*/Dexclassloader CL=NewDexclassloader (Dexpath,dexoutputdirs.getabsolutepath (),NULL, This. getClassLoader ()); Try{Class<?> Libproviderclazz = Cl.loadclass ("Com.example.test.Dynamic"); Lib=(idynamic) libproviderclazz.newinstance (); } Catch(Exception Exception) {exception.printstacktrace (); }        returnLib; }}

5. Package and convert to Dex

Select the dynamic class, right--and Export-to-Jar file

Copy the packaged jar to the SDK installation directory Android-sdk-windows\platform-tools,

But found that the current SDK in this directory has no DX files, and was transferred to \build-tools\21.1.1 under

My directory is: D:\android_sdk\build-tools\21.1.1, this depends on the individual, each person installs the location not necessarily the same

Then say, run the dos cmd command line into this directory

Execute command:

DX--dex--output=dynamic.jar Test.jar

After that, copy the Test.jar to the SDcard root directory.

Paste Mainactivity Loading Jar code

    /*** Load sdcard with directory Test.jar *@returnidynamic*/     Publicidynamic loadclass () {idynamic lib=NULL; String Dexpath= Environment.getexternalstoragedirectory (). toString () + File.separator + "Test.jar"; File Dexoutputdirs= This. Getapplicationcontext (). Getdir ("Dex", 0); /*** Dexpath The path of the APK or jar file that needs to be loaded. Contains multiple paths separated by File.pathseparator, on Android The default is ":" Optimizeddirectory optimized dex file storage directory, cannot be null LibraryPath target A list of C + + libraries used in the class, with each directory separated by File.pathseparator; can be null parent loader for the class loader, typically with the loader of the currently executing class*/Dexclassloader CL=NewDexclassloader (Dexpath,dexoutputdirs.getabsolutepath (),NULL, This. getClassLoader ()); Try{Class<?> Libproviderclazz = Cl.loadclass ("Com.example.test.Dynamic"); Lib=(idynamic) libproviderclazz.newinstance (); } Catch(Exception Exception) {exception.printstacktrace (); }        returnLib; }

Paste mainactivity code to invoke the Init () method in the Jar

        Variable.testvalue = "heaven and earth heartless, with all things as a humble dog";                 = (TextView) Findviewbyid (R.id.click);        Click.setonclicklistener (new  Onclicklistener () {                        @Override            public  void  OnClick (View v) {                //  TODO auto-generated method stub                loadclass ( ). Init (mainactivity.  this);}        );

6. Running

Before running: Remove the Dynamic.java file from the project, then know that the code was successfully called to the Dynamic.java in the jar.

"Heaven and earth are unkind to all things for the dog" shows that the TestValue variable in the variable can be called in the jar

Reference article:

android dynamic load Jar/dex

Android plugin dynamic loading jar

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.