Preface
In the current software and hardware environment, Native apps and Web apps have obvious advantages in user experience, but in actual projects, some clients are frequently upgraded due to frequent business changes, this results in poor user experience, which is precisely the advantage of Web apps. This article will sort out and share with you the information about how Android dynamically loads jar files on the Internet, and try to improve the frequent upgrade.
Statement
You are welcome to repost, but please keep the original source of the article :)
Blog: http://www.cnblogs.com
Farmer's uncle: http://over140.cnblogs.com
Android Chinese translation group: http://androidbox.sinaapp.com/
Body
I. Basic Concepts and notes
1.1 first, you need to know: Android can be dynamically loaded, but it cannot be as convenient as in Java to dynamically load jar
Cause: the Android Virtual Machine (Dalvik VM) does not know the byte code of jar output by Java. It must be optimized and converted to Dalvik byte code by using the dx tool. In the apk package of the Android project, we can see that the contents of other Jar files are packaged into classes. dex.
Therefore, this road is unavailable. Please note that.
1.2 which APIS can be used for Dynamic Loading
1.2.1 DexClassLoader
This can load jar/apk/dex, or load from the SD card, which is also the focus of this article.
1.2.3 PathClassLoader
Only apk files that have been installed in Android can be loaded.
2. Preparation
This article mainly refers to the first article in "4. References" to add details and practices.
2.1 Download an open-source project
Http://code.google.com/p/goodev-demo
Import the project to the project. If the project reports an error, the gen folder is missing and you can add it manually. Note that this example downloads the optimized jar (which has been optimized to dex and then packaged into a jar) from the Internet to the local file system, and then loads and calls it from the local file system. This article is changed to loading from the SD card.
Iii. Practice
3.1 write interfaces and implementation
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 package and convert to dex
3.2.1 select a project and export the general process,
Note: in practice, it is found that creating a Java project and exporting the jar file by yourself are not usable. You can refer to the article to learn the relevant reasons, which is also one of the key points of this article. Package and export it as dynamic. jar
(Post-fix: do not include the interface file in the package. For details, refer to the subsequent maintenance at the end of the article !)
3.2.2 copy the packaged jar file to the android-SDK-windows \ platform-tools directory of the sdk installation directory. Enter the DOS directory and name it:
Dx -- dex -- output = test. jar dynamic. jar
3.3 modify call example
Modify 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 be 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 the required dex file from the network
// (New preparedextask(cmd.exe cute (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.
// 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.
// Load the class 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 that
// 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. References
[Recommended] dynamically load custom classes in Android
Load the jar plug-in Android app
ClassLoader exploration for Android
How to dynamically load classes in Android apps
5. Supplement
You can refer to the API documentation of DexClassLoader, which does not advocate loading from the SD card and is not safe. In addition, I am also organizing a translation group to translate several classes in this namespace as soon as possible for your reference.
Download project: Here, download Dex file: Here. You can directly copy the Dex file to the SD card and run the example.
Vi. Post-Maintenance
6.1 2011-12-1 fixed the error in this article
Thanks for the feedback from ppp250 and liuzhaocn, which was modified in accordance with comment 2:
6.1.1 you do not need to export the jar in this project. Create a New Java project and export it as well.
6.1.2 when exporting jar files, the interface file cannot be included; otherwise, the following error is reported:
Java. lang. IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
6.1.3 during jar optimization, it should be re-converted to jar (jar-> dex-> jar), if the following command:
Dx -- dex -- output = test. jar dynamic. jar
6.2 this article upgraded:
Android Application Development and Improvement series (4) -- Android dynamic loading (on) -- loading classes not installed in APK
Please refer to the latest articles for dynamic loading!
End
In addition to the translation team's work and their own work, it is difficult to take time out to share some development experiences, but the so-called "crowded" is always there, welcome to exchange!