Http://www.cnblogs.com/over140/archive/2011/11/23/2259367.html
Objective
In the current hardware and software environment, Native app and web app have obvious advantages in user experience, but in the actual project some will frequently upgrade the client because of frequent business changes, resulting in poor user experience, and this is precisely the advantage of web App. This article combs and practices the data of the dynamic loading jar of Android on-line here to share with you, trying to improve the disadvantage of frequent upgrade.
Statement
Welcome reprint, but please keep the original source of the article:)
Blog Park: http://www.cnblogs.com
Farmer Uncle: Http://over140.cnblogs.com
Android Chinese translation group: http://androidbox.sinaapp.com/
Body
I. Basic concepts and points of attention
1.1 First thing you need to know: Dynamic loading in Android, but it's not as easy as Java to load jars dynamically
Cause: 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 is what 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.
So this road is not through, please pay attention.
1.2 What APIs are currently available for dynamic loading
1.2.1 Dexclassloader
This can be loaded Jar/apk/dex, can also be loaded from the SD card, is also the focus of this article.
1.2.3 Pathclassloader
You can only load apk files that are already installed on your Android system.
Second, prepare
This article mainly refers to the "four, reference article" in the first article, to supplement the details and practice process.
2.1 Download Open Source project
Http://code.google.com/p/goodev-demo
The project into project, the project error should be less the Gen folder, manually add can. Note that this example is to download the optimized jar from the Web (which has been optimized to Dex and then packaged into a jar) to the local file system and then loaded and invoked from the local filesystem. This article is directly changed to load from SD card.
Third, practice
3.1 Authoring interfaces and implementations
3.1.1 Interface idynamic
Package com.dynamic;
Public interface Idynamic {
Public String HelloWorld ();
}
3.1.2 Implementation class Dynamictest
Package com.dynamic;
public class Dynamictest implements Idynamic {
@Override
Public String HelloWorld () {
Return "Hello world!";
}
}
3.2 Pack and turn into Dex
3.2.1 Selected project, general process export can,
Note: In practice, found that you create a new Java project and then export the jar is not available, this can be based on the article to understand the relevant reasons, is also one of the focus of this article. This package is exported as Dynamic.jar
(Post-Repair: Please do not put the interface file in the package, see the article at the end of the follow-up maintenance!) )
3.2.2 The packaged jar copy to the SDK installation directory Android-sdk-windows\platform-tools, DOS enters this directory and executes the name:
DX--dex--output=test.jar Dynamic.jar
3.3 Modifying the invocation example
Modify the mainactivity as follows:
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Mtoastbutton = (Button) Findviewbyid (R.id.toast_button);
Before the secondary Dex file can be processed by the Dexclassloader,
It has to is first copied from asset resource to a storage location.
Final file Dexinternalstoragepath = new file (Getdir ("Dex", Context.mode_private), secondary_dex_name);
if (!dexinternalstoragepath.exists ()) {
Mprogressdialog = Progressdialog.show (This,
Getresources (). getString (R.string.diag_title),
Getresources (). getString (R.string.diag_message), true, false);
Perform the file copying in an asynctask.
Download required DEX files from the network
(New Preparedextask ()). Execute (Dexinternalstoragepath);
} else {
Mtoastbutton.setenabled (TRUE);
// }
Mtoastbutton.setonclicklistener (New View.onclicklistener () {
public void OnClick (view view) {
Internal storage where the Dexclassloader writes the optimized Dex file to.
Final File Optimizeddexoutputpath = Getdir ("Outdex", context.mode_private);
Final file Optimizeddexoutputpath = new file (Environment.getexternalstoragedirectory (). ToString ()
+ File.separator + "Test.jar");
Initialize the class loader with the secondary Dex file.
Dexclassloader cl = new Dexclassloader (Dexinternalstoragepath.getabsolutepath (),
Optimizeddexoutputpath.getabsolutepath (),
Null
getClassLoader ());
Dexclassloader cl = new Dexclassloader (Optimizeddexoutputpath.getabsolutepath (),
Environment.getexternalstoragedirectory (). toString (), NULL, getClassLoader ());
Class libproviderclazz = null;
try {
Load the Library class from the class loader.
Loading classes downloaded from the network
Libproviderclazz = Cl.loadclass ("Com.example.dex.lib.LibraryProvider");
Libproviderclazz = Cl.loadclass ("Com.dynamic.DynamicTest");
Cast the return object to the library interface so
Caller can directly invoke methods in the interface.
Alternatively, the caller can invoke methods through reflection,
Which is more verbose and slow.
Libraryinterface lib = (libraryinterface) libproviderclazz.newinstance ();
Idynamic lib = (idynamic) libproviderclazz.newinstance ();
Display the toast!
Lib.showawesometoast (View.getcontext (), "Hello World!");
Toast.maketext (Mainactivity.this, Lib.helloworld (), Toast.length_short). Show ();
} catch (Exception Exception) {
Handle exception gracefully here.
Exception.printstacktrace ();
}
}
});
}
3.4 Execution Results
Iv. Reference Articles
[Recommended] Dynamically loading custom classes in Android
Loading the jar plugin in Android app
Explore ClassLoader on Android
How Android App loads classes dynamically
V. Supplementary
Everyone can look at Dexclassloader API documentation, which does not advocate loading from SD card, unsafe. In addition, I am also organizing the translation team as soon as possible to the namespace under the several classes are translated, for your reference.
Project Download: Here, dex file download: here. You can copy the Dex file directly to the SD card and run the example.
Six, late maintenance
6.1 2011-12-1 fix this article error
Thank netizens ppp250 and liuzhaocn feedback, basically in accordance with the comments and modify:
6.1.1 do not need to export the jar in this project, create a new Java project and then export it.
6.1.2 The jar cannot be exported with an interface file, otherwise the following error will be reported:
Java.lang.IllegalAccessError:Class ref in Pre-verified Class resolved to unexpected implementation
The 6.1.3 should be re-jar->dex->jar when the jar is optimized, if the following command:
DX--dex--output=test.jar Dynamic.jar
6.2 2012-3-29 This article is an upgraded version:
Android App development Boost series (4)--android dynamic load (top)--load the class from the APK that is not installed
Please refer to the latest articles to do dynamic loading!
End
In addition to the work of the translation team and their own work, it is difficult to take time to share some development experience, but is so-called squeeze always have, welcome to exchange!
Android Dynamic load Jar/dex