自己动手写Android插件化框架,让老板对你刮目相看
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~
最近在工作中接触到了android插件内的开发,发现自己这种技术还缺乏最基本的了解,以至于在一些基本问题上浪费不少时间,如插件context和主工程context的区别,权限必须在主工程申明等,因此花了点时间了解了一下插件的历史,并写了两个demo作为总结。本文旨在通过两个实例直观的说明插件的实现原理以加深对插件内开发的理解,因此不会深入探讨背景和原理,代码也尽量专注于核心逻辑。
原理与背景
android插件化从技术上来说就是如何启动未安装的apk(主要是四大组件)里面的类,主要问题涉及如何加载类、如何加载资源、如何管理组件生命周期。
类加载
android对于外部的dex文件,主要通过dexclassloader
类加载,因此,只需要给定插件的路径,就可以构造对应的类加载器:
private dexclassloader createdexclassloader(string apkpath) { file dexoutputdir = mcontext.getdir("dex", context.mode_private); dexclassloader loader = new dexclassloader(apkpath, dexoutputdir.getabsolutepath(), null, mcontext.getclassloader()); return loader; }
资源加载
android系统通过resource对象加载资源,因此只需要添加资源(即apk文件)所在路径到assetmanager
中,即可实现对插件资源的访问。
assetmanager assetmanager = assetmanager.class.newinstance(); method addassetpath = assetmanager.getclass().getmethod(addassetpathmethod, string.class); addassetpath.invoke(assetmanager, apkpath); resources pluginres = new resources(assetmanager, mcontext.getresources().getdisplaymetrics(), mcontext.getresources().getconfiguration()); pluginapk = new pluginapk(pluginres); pluginapk.classloader = createdexclassloader(apkpath);
生命周期
插件化中较为复杂的是对生命周期的管理,其中以activity最为复杂。早期的dynamic-load-apk采用的是代理的方式,通过一个空壳activity作为代理(proxy),系统对该activity的回调都会映射到插件activity,如此便可以实现通过系统来管理插件的生命周期。这种方式十分直观,但是需要所有的插件activity都继承这个用作代理的pluginactivity
(demo中的命名),侵入性强,可结合后面的例子加深理解。因此,如何避免这种侵入性成了第二代插件化框架的目标,virtualapk通过hook少量系统类达到了这个目标,插件的开发和普通工程无异,接入成本极低。
了解了这些原理往往还不够,知识往往需要经过推导和实践才能变成自己的,因此,接下来我们结合这些原理来实现一个插件化框架,不考虑兼容性和健壮性,纯粹来实践上面提及的原理。
代理实现
首先建立一个pluginmanager
类来实现插件的加载:
public class pluginmanager { static class pluginmgrholder { static pluginmanager smanager = new pluginmanager(); } private static context mcontext; map<string, pluginapk> smap = new hashmap<>(); public static pluginmanager getinstance() { return pluginmgrholder.smanager; } public pluginapk getpluginapk(string packagename) { return smap.get(packagename); } public static void init(context context) { mcontext = context.getapplicationcontext(); } public final void loadapk(string apkpath) { packageinfo packageinfo = querypackageinfo(apkpath); if (packageinfo == null || textutils.isempty(packageinfo.packagename)) { return; } // check cache pluginapk pluginapk = smap.get(packageinfo.packagename); if (pluginapk == null) { pluginapk = createapk(apkpath); if (pluginapk != null) { pluginapk.packageinfo = packageinfo; smap.put(packageinfo.packagename, pluginapk); } else { throw new nullpointerexception("pluginapk is null"); } } } private pluginapk createapk(string apkpath) { string addassetpathmethod = "addassetpath"; pluginapk pluginapk = null; try { assetmanager assetmanager = assetmanager.class.newinstance(); method addassetpath = assetmanager.getclass().getmethod(addassetpathmethod, string.class); addassetpath.invoke(assetmanager, apkpath); resources pluginres = new resources(assetmanager, mcontext.getresources().getdisplaymetrics(), mcontext.getresources().getconfiguration()); pluginapk = new pluginapk(pluginres); pluginapk.classloader = createdexclassloader(apkpath); } catch (illegalaccessexception | instantiationexception | nosuchmethodexception | invocationtargetexception e) { e.printstacktrace(); } return pluginapk; } private packageinfo querypackageinfo(string apkpath) { packageinfo packageinfo = mcontext.getpackagemanager().getpackagearchiveinfo(apkpath, packagemanager.get_activities | packagemanager.get_services); if (packageinfo == null) { return null; } return packageinfo; } private dexclassloader createdexclassloader(string apkpath) { file dexoutputdir = mcontext.getdir("dex", context.mode_private); dexclassloader loader = new dexclassloader(apkpath, dexoutputdir.getabsolutepath(), null, mcontext.getclassloader()); return loader; } public void startactivity(intent intent) { intent pluginintent = new intent(mcontext, proxyactivity.class); bundle extra = intent.getextras(); // complicate if statement if (extra == null || !extra.containskey(constants.plugin_class_name) && !extra.containskey(constants.package_name)) { try { throw new illegalaccessexception("lack class of plugin and package name"); } catch (illegalaccessexception e) { e.printstacktrace(); } } pluginintent.putextras(intent); pluginintent.setflags(intent.flag_activity_new_task); mcontext.startactivity(pluginintent); } }
pluginapk
表示一个apk文件:
public class pluginapk { public packageinfo packageinfo; public dexclassloader classloader; public resources pluginres; public pluginapk(resources pluginres) { this.pluginres = pluginres; } }
所有插件activity都要继承一个父类pluginactivity
:
public abstract class pluginactivity extends activity implements pluginable, attachable<activity> { public final static string tag = pluginactivity.class.getsimplename(); protected activity mproxyactivity; private resources mresources; pluginapk mpluginapk; @override public void attach(activity proxy, pluginapk apk) { mproxyactivity = proxy; mpluginapk = apk; mresources = apk.pluginres; } @override public void setcontentview(int layoutresid) { mproxyactivity.setcontentview(layoutresid); } @override public void setcontentview(view view) { mproxyactivity.setcontentview(view); } @override public void setcontentview(view view, viewgroup.layoutparams params) { mproxyactivity.setcontentview(view, params); } @override public view findviewbyid(int id) { return mproxyactivity.findviewbyid(id); } @override public resources getresources() { return mresources; } @override public windowmanager getwindowmanager() { return mproxyactivity.getwindowmanager(); } @override public classloader getclassloader() { return mproxyactivity.getclassloader(); } @override public context getapplicationcontext() { return mproxyactivity.getapplicationcontext(); } @override public menuinflater getmenuinflater() { return mproxyactivity.getmenuinflater(); } @override public window getwindow() { return mproxyactivity.getwindow(); } @override public intent getintent() { return mproxyactivity.getintent(); } @override public layoutinflater getlayoutinflater() { return mproxyactivity.getlayoutinflater(); } @override public string getpackagename() { return mpluginapk.packageinfo.packagename; } @override public void oncreate(bundle bundle) { // do not call super.oncreate(bundle) // following same vlog.log(tag + ": oncreate"); } @override public void onstart() { } @override public void onresume() { } @override public void onstop() { } @override public void onpause() { } @override public void ondestroy() { } }
这个类只是一个壳,系统会通过proxyactivity
触发对应的方法的具体实现:
public class proxyactivity extends activity { lifecirclecontroller mplugincontroller = new lifecirclecontroller(this); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mplugincontroller.oncreate(getintent().getextras()); } @override public resources getresources() { // construct when loading apk resources resources = mplugincontroller.getresources(); return resources == null ? super.getresources() : resources; } @override public resources.theme gettheme() { resources.theme theme = mplugincontroller.gettheme(); return theme == null ? super.gettheme() : theme; } @override public assetmanager getassets() { return mplugincontroller.getassets(); } @override protected void onstart() { super.onstart(); mplugincontroller.onstart(); } @override protected void onresume() { super.onresume(); mplugincontroller.onresume(); } @override protected void onstop() { super.onstop(); mplugincontroller.onstop(); } @override protected void onpause() { super.onpause(); mplugincontroller.onpause(); } @override protected void ondestroy() { super.ondestroy(); mplugincontroller.ondestroy(); } }
这个类是系统实际启动的类,其主要逻辑由lifecirclecontroller
负责:
public class lifecirclecontroller implements pluginable { activity mproxy; pluginactivity mplugin; resources mresources; resources.theme mtheme; pluginapk mpluginapk; string mpluginclazz; public lifecirclecontroller(activity activity) { mproxy = activity; } public void oncreate(bundle bundle) { mpluginclazz = bundle.getstring(constants.plugin_class_name); string packagename = bundle.getstring(constants.package_name); mpluginapk = pluginmanager.getinstance().getpluginapk(packagename); try { mplugin = (pluginactivity) loadpluginable(mpluginapk.classloader, mpluginclazz); mplugin.attach(mproxy, mpluginapk); mresources = mpluginapk.pluginres; mplugin.oncreate(bundle); } catch (exception e) { vlog.log("fail in lifecirclecontroller oncreate"); vlog.log(e.getmessage()); e.printstacktrace(); } } private object loadpluginable(classloader classloader, string pluginactivityclass) throws exception { class<?> pluginclz = classloader.loadclass(pluginactivityclass); constructor<?> constructor = pluginclz.getconstructor(new class[] {}); constructor.setaccessible(true); return constructor.newinstance(new object[] {}); } @override public void onstart() { if (mplugin != null) { mplugin.onstart(); } } @override public void onresume() { if (mplugin != null) { mplugin.onresume(); } } @override public void onstop() { mplugin.onstop(); } @override public void onpause() { mplugin.onpause(); } @override public void ondestroy() { mplugin.ondestroy(); } public resources getresources() { return mresources; } public resources.theme gettheme() { return mtheme; } public assetmanager getassets() { return mresources.getassets(); } }
有点像activity源码的外观模式,内部的分工和职责划分对于使用者是不可见的。
最后在主工程启动插件:
intent intent = new intent(); intent.putextra(constants.package_name, plugin_package_name); intent.putextra(constants.plugin_class_name, plugin_clazz_name); mpluginmanager.startactivity(intent);
插件activity如下:
public class mainactivity extends pluginactivity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); settitle("plugin app"); ((imageview) findviewbyid(r.id.iv_logo)).setimageresource(r.drawable.android); } }
效果:
hook实现
hook的方式需要基本了解系统启动一个activity的过程,一般来说系统会先检查activity是否注册,然后再去生成该activity,那么我们只需要在检查的时候用一个已经注册的activity(桩,通常表示为stubactivity)来给系统检查,检查通过后在生成的时候再替换成插件的就可以了。
首先要自己实现一个instrumentation
,在里面做一些替换工作,然后去hook掉系统持有的对象:
public class hookedinstrumentation extends instrumentation implements handler.callback { public static final string tag = "hookedinstrumentation"; protected instrumentation mbase; private pluginmanager mpluginmanager; public hookedinstrumentation(instrumentation base, pluginmanager pluginmanager) { mbase = base; mpluginmanager = pluginmanager; } /** * 覆盖掉原始instrumentation类的对应方法,用于插件内部跳转activity时适配 * * @override */ public activityresult execstartactivity( context who, ibinder contextthread, ibinder token, activity target, intent intent, int requestcode, bundle options) { if (constants.debug) log.e(tag, "execstartactivity"); mpluginmanager.hooktostubactivity(intent); try { method execstartactivity = instrumentation.class.getdeclaredmethod( "execstartactivity", context.class, ibinder.class, ibinder.class, activity.class, intent.class, int.class, bundle.class); execstartactivity.setaccessible(true); return (activityresult) execstartactivity.invoke(mbase, who, contextthread, token, target, intent, requestcode, options); } catch (exception e) { e.printstacktrace(); throw new runtimeexception("do not support!!!" + e.getmessage()); } } @override public activity newactivity(classloader cl, string classname, intent intent) throws instantiationexception, illegalaccessexception, classnotfoundexception { if (constants.debug) log.e(tag, "newactivity"); if (mpluginmanager.hooktopluginactivity(intent)) { string targetclassname = intent.getcomponent().getclassname(); pluginapp pluginapp = mpluginmanager.getloadedpluginapk(); activity activity = mbase.newactivity(pluginapp.mclassloader, targetclassname, intent); activity.setintent(intent); reflectutil.setfield(contextthemewrapper.class, activity, constants.field_resources, pluginapp.mresources); return activity; } if (constants.debug) log.e(tag, "super.newactivity(...)"); return super.newactivity(cl, classname, intent); } @override public boolean handlemessage(message message) { if (constants.debug) log.e(tag, "handlemessage"); return false; } @override public void callactivityoncreate(activity activity, bundle icicle) { if (constants.debug) log.e(tag, "callactivityoncreate"); super.callactivityoncreate(activity, icicle); } }
在负责启动的execstartactivity
设置为启动已注册的activity,再在newactivity
设置为实际要启动的插件的activity。然后去hook系统持有的该字段:
public class reflectutil { public static final string method_currentactivitythread = "currentactivitythread"; public static final string class_activitythread = "android.app.activitythread"; public static final string field_minstrumentation = "minstrumentation"; public static final string tag = "reflectutil"; private static instrumentation sinstrumentation; private static instrumentation sactivityinstrumentation; private static field sactivitythreadinstrumentationfield; private static field sactivityinstrumentationfield; private static object sactivitythread; public static boolean init() { //获取当前的activitythread对象 class<?> activitythreadclass = null; try { activitythreadclass = class.forname(class_activitythread); method currentactivitythreadmethod = activitythreadclass.getdeclaredmethod(method_currentactivitythread); currentactivitythreadmethod.setaccessible(true); object currentactivitythread = currentactivitythreadmethod.invoke(null); //拿到在activitythread类里面的原始minstrumentation对象 field instrumentationfield = activitythreadclass.getdeclaredfield(field_minstrumentation); instrumentationfield.setaccessible(true); sactivitythreadinstrumentationfield = instrumentationfield; sinstrumentation = (instrumentation) instrumentationfield.get(currentactivitythread); sactivitythread = currentactivitythread; sactivityinstrumentationfield = activity.class.getdeclaredfield(field_minstrumentation); sactivityinstrumentationfield.setaccessible(true); return true; } catch (classnotfoundexception | nosuchmethodexception | illegalaccessexception | invocationtargetexception | nosuchfieldexception e) { e.printstacktrace(); } return false; } public static instrumentation getinstrumentation() { return sinstrumentation; } public static object getactivitythread() { return sactivitythread; } public static void setinstrumentation(object activitythread, hookedinstrumentation hookedinstrumentation) { try { sactivitythreadinstrumentationfield.set(activitythread, hookedinstrumentation); if (constants.debug) log.e(tag, "set hooked instrumentation"); } catch (illegalaccessexception e) { e.printstacktrace(); } } public static void setactivityinstrumentation(activity activity, pluginmanager manager) { try { sactivityinstrumentation = (instrumentation) sactivityinstrumentationfield.get(activity); hookedinstrumentation instrumentation = new hookedinstrumentation(sactivityinstrumentation, manager); sactivityinstrumentationfield.set(activity, instrumentation); if (constants.debug) log.e(tag, "set activity hooked instrumentation"); } catch (illegalaccessexception e) { e.printstacktrace(); } } public static void setfield(class clazz, object target, string field, object object) { try { field f = clazz.getdeclaredfield(field); f.setaccessible(true); f.set(target, object); } catch (exception e) { e.printstacktrace(); } } }
pluginmanager
同样负责加载插件的类和资源等:
public class pluginmanager { private final static string tag = "pluginmanager"; private static pluginmanager sinstance; private context mcontext; private pluginapp mpluginapp; public static pluginmanager getinstance(context context) { if (sinstance == null && context != null) { sinstance = new pluginmanager(context); } return sinstance; } private pluginmanager(context context) { mcontext = context; } public void hookinstrumentation() { try { instrumentation baseinstrumentation = reflectutil.getinstrumentation(); final hookedinstrumentation instrumentation = new hookedinstrumentation(baseinstrumentation, this); object activitythread = reflectutil.getactivitythread(); reflectutil.setinstrumentation(activitythread, instrumentation); } catch (exception e) { e.printstacktrace(); } } public void hookcurrentactivityinstrumentation(activity activity) { reflectutil.setactivityinstrumentation(activity, sinstance); } public void hooktostubactivity(intent intent) { if (constants.debug) log.e(tag, "hooktostubactivity"); if (intent == null || intent.getcomponent() == null) { return; } string targetpackagename = intent.getcomponent().getpackagename(); string targetclassname = intent.getcomponent().getclassname(); if (mcontext != null && !mcontext.getpackagename().equals(targetpackagename) && ispluginloaded(targetpackagename)) { if (constants.debug) log.e(tag, "hook " + targetclassname + " to " + constants.stub_activity); intent.setclassname(constants.stub_package, constants.stub_activity); intent.putextra(constants.key_is_plugin, true); intent.putextra(constants.key_package, targetpackagename); intent.putextra(constants.key_activity, targetclassname); } } public boolean hooktopluginactivity(intent intent) { if (constants.debug) log.e(tag, "hooktopluginactivity"); if (intent.getbooleanextra(constants.key_is_plugin, false)) { string pkg = intent.getstringextra(constants.key_package); string activity = intent.getstringextra(constants.key_activity); if (constants.debug) log.e(tag, "hook " + intent.getcomponent().getclassname() + " to " + activity); intent.setclassname(pkg, activity); return true; } return false; } private boolean ispluginloaded(string packagename) { // todo 检查packagenmae是否匹配 return mpluginapp != null; } public pluginapp loadpluginapk(string apkpath) { string addassetpathmethod = "addassetpath"; pluginapp pluginapp = null; try { assetmanager assetmanager = assetmanager.class.newinstance(); method addassetpath = assetmanager.getclass().getmethod(addassetpathmethod, string.class); addassetpath.invoke(assetmanager, apkpath); resources pluginres = new resources(assetmanager, mcontext.getresources().getdisplaymetrics(), mcontext.getresources().getconfiguration()); pluginapp = new pluginapp(pluginres); pluginapp.mclassloader = createdexclassloader(apkpath); } catch (illegalaccessexception | instantiationexception | nosuchmethodexception | invocationtargetexception e) { e.printstacktrace(); } return pluginapp; } private dexclassloader createdexclassloader(string apkpath) { file dexoutputdir = mcontext.getdir("dex", context.mode_private); return new dexclassloader(apkpath, dexoutputdir.getabsolutepath(), null, mcontext.getclassloader()); } public boolean loadplugin(string apkpath) { file apk = new file(apkpath); if (!apk.exists()) { return false; } mpluginapp = loadpluginapk(apkpath); return mpluginapp != null; } public pluginapp getloadedpluginapk() { return mpluginapp; } }
在mainactivity中初始化,注意hook的时机:
public class mainactivity extends activity implements view.onclicklistener { // https://zhuanlan.zhihu.com/p/33017826 public static final boolean debug = true; public static final string tag = "mainactivity"; private string mpluginpackagename = "top.vimerzhao.image"; private string mpluginclassname = "top.vimerzhao.image.mainactivity"; //读写权限 private static string[] permissions_storage = {manifest.permission.read_external_storage, manifest.permission.write_external_storage}; //请求状态码 private static int request_permission_code = 1; private pluginmanager mpluginmanager; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); initdata(); initview(); initplugin(); } private void initplugin() { // !! must first reflectutil.init(); mpluginmanager = pluginmanager.getinstance(getapplicationcontext()); mpluginmanager.hookinstrumentation(); mpluginmanager.hookcurrentactivityinstrumentation(this); } private void initdata() { if (build.version.sdk_int > build.version_codes.lollipop) { if (activitycompat.checkselfpermission(this, manifest.permission.write_external_storage) != packagemanager.permission_granted) { activitycompat.requestpermissions(this, permissions_storage, request_permission_code); } } } private void initview() { (findviewbyid(r.id.tv_launch)).setonclicklistener(this); } @override protected void attachbasecontext(context newbase) { super.attachbasecontext(newbase); // !!! 不要在此hook,看源码发现minstrumentaion会在此方法后初始化 } @override public void onclick(view view) { if (constants.debug) log.e(tag, "click view id: " + view.getid()); if (view.getid() == r.id.tv_launch) { // todo launch plugin app if (mpluginmanager.loadplugin(constants.plugin_path)) { intent intent = new intent(); intent.setclassname(mpluginpackagename, mpluginclassname); startactivity(intent); } } } }
现在插件activity不会有任何限制:
public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } @override protected void onresume() { super.onresume(); } }
效果和上图类似。
demo地址
部分源码无关核心逻辑,没有给到,目录结构也没有说明,详见demo源码。
总结
看着理论感觉似懂非懂,实战发现问题其实挺多的,尤其是hook的时机,照搬网上的文章发现根本不可行。插件化也不是一蹴而就的,而是在已有成果的基础上一次一次的小创新积累起来的,跟着插件化发展的路径自己动手实践一遍还是能发现很多自己理解不够深刻的地方的。
以上。
参考
- 《android源码设计模式解析与实战》
- 深入理解android插件化技术
相关阅读
获得inputstream,读取配置文件的方式
聊聊springboot session timeout参数设置
android开发之漫漫长途 xii——fragment详解
【每日课程推荐】机器学习实战!快速入门在线广告业务及ctr相应知识
此文已由作者授权腾讯云+社区发布,更多原文请点击
搜索关注公众号「云加社区」,第一时间获取技术干货,关注后回复1024 送你一份技术课程大礼包!
海量技术实践经验,尽在云加社区!
上一篇: jQuery实现轮播图效果
下一篇: adb连接国产模拟器