Android Dynamic Module Lập trình module động trong Android Phí Ngọc Chi – CTO Eway JSC [email protected] | facebook.com/phingocchi
Android Dynamic ModuleLập trình module động trong Android
Phí Ngọc Chi – CTO Eway JSC
[email protected] | facebook.com/phingocchi
Cập nhật Ứng Dụng Android
APK
Module v 2.0
…
…
,,,
APK
Module v 1.0
…
…
…
ClientServer
Cập nhật Module
APK
Module v 2.0
APK
Module v 1.0
…
…
…
ClientServer
Ưu điểm cập nhật theo Module
Mềm dẻo và linh động Khả năng mở rộng tốt Đơn giản hóa việc cập nhật với người
dùng Dung lượng cập nhật nhỏ Tốc độ cập nhật nhanh tức thời
Dynamic Module
Module được phát triển như một project độc lập và đóng gói thành file module.apk
Ứng dụng chính tải file module.apk từ URL DexClassLoader: thư viện sử dụng để nạp
class động từ file module.apk Java Reflection: khởi tạo object từ class động
và tương tác với object để kích hoạt logic thực thi
Quy trình cập nhật Module
APK
Module
DexC
lassLo
ade
r
Module.apk – v1.0
Module.apk – v2.0
…
Java R
eflect
ion
Load Module Class
New Instance
Invoke Method
Download Module Load Module Active Module
DemoModule Code
public class DemoModule { public void show() { Toast.makeText(getApplicationContext(), "Hi! version 1.0", Toast.LENGTH_SHORT).show(); }}
public class DemoModule{ public void show() { AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.setMessage("Hi! version 2.0"); dialog.show(); }}
DemoModule.apk - v1.0 DemoModule.apk – v2.0
Download DemoModule
public void downloadDemoModule(Context context) { String dexPath = new File(context.getDir("dex", Context.MODE_PRIVATE), "DemoModule.apk").getAbsolutePath();
//TODO: download DemoModule.apk from URL to dexPath File}
Load DemoModule
public DexClassLoader getDemoModuleClassLoader(Context context) { String dexPath = new File(context.getDir("dex", Context.MODE_PRIVATE), "DemoModule.apk").getAbsolutePath(); String optimizedDirectory = context.getDir("temp", 0).toString(); String libraryPath = null; ClassLoader parent ClassLoader = context.getClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader(dexPath, optimizedDirectory, libraryPath, parentClassLoader); return dexClassLoader; }
Active DemoModule
DexClassLoader classLoader = this.getDemoModuleClassLoader(this);try { Class<?> demoModuleClass = classLoader.loadClass("com.simple.DemoModule"); Object demoModule = demoModuleClass.newInstance(); demoModuleClass.getMethod("show").invoke(demoModule);} catch (Exception ex) { ex.printStackTrace();}
DemoModule Screenshot