Android系统实现DroidPlugin插件机制
360手机助手使用的 droidplugin,它是360手机助手团队在android系统上实现了一种插件机制。它可以在无需安装、修改的情况下运行apk文件,此机制对改进大型app的架构,实现多团队协作开发具有一定的好处。
它是一种新的插件机制,一种免安装的运行机制
github地址:https://github.com/droidpluginteam/droidplugin
参考博客:http://blog.csdn.net/hejjunlin/article/details/52124397
droidplugin的的基本原理:
共享进程:为android提供一个进程运行多个apk的机制,通过api欺骗机制瞒过系统
占坑:通过预先占坑的方式实现不用在manifest注册,通过一带多的方式实现服务管理
hook机制:动态代理实现函数hook,binder代理绕过部分系统服务限制,io重定向(先获取原始object-->read,然后动态代理hook object后-->write回去,达到瞒天过海的目的)
public abstract class hook { private boolean menable = false;//能否hook protected context mhostcontext;//宿主context,外部传入 protected basehookhandle mhookhandles; public void setenable(boolean enable, boolean reinstallhook) { this.menable = enable; } public final void setenable(boolean enable) { setenable(enable, false); } public boolean isenable() { return menable; } protected hook(context hostcontext) { mhostcontext = hostcontext; mhookhandles = createhookhandle(); } protected abstract basehookhandle createhookhandle();//用于子类创建hook机制 protected abstract void oninstall(classloader classloader) throws throwable;//插件安装 protected void onuninstall(classloader classloader) throws throwable {//插件卸载 } }
public class hookedmethodhandler {//hook方法 private static final string tag = hookedmethodhandler.class.getsimplename(); protected final context mhostcontext; /** * 调用方法的时候会到appopsservice进行判断uid(宿主apk)和插件的包名是否匹配,此处是不匹配的 * 此时就可以经过转换欺骗系统让程序认为是宿主apk调过来的(这样的前提就需要宿主把所有的权限都申请了) * 因为系统只会去检测宿主apk * **/ private object mfakedresult = null;//用于欺骗系统 private boolean musefakedresult = false; public hookedmethodhandler(context hostcontext) { this.mhostcontext = hostcontext; } public synchronized object dohookinner(object receiver, method method, object[] args) throws throwable { long b = system.currenttimemillis(); try { musefakedresult = false; mfakedresult = null; boolean suc = beforeinvoke(receiver, method, args); object invokeresult = null; if (!suc) {//false执行原始方法 invokeresult = method.invoke(receiver, args); } afterinvoke(receiver, method, args, invokeresult); if (musefakedresult) {//true返回欺骗结果,false返回正常的调用方法 return mfakedresult; } else { return invokeresult; } } finally { long time = system.currenttimemillis() - b; if (time > 5) { log.i(tag, "dohookinner method(%s.%s) cost %s ms", method.getdeclaringclass().getname(), method.getname(), time); } } } public void setfakedresult(object fakedresult) { this.mfakedresult = fakedresult; musefakedresult = true; } /** * 在某个方法被调用之前执行,如果返回true,则不执行原始的方法,否则执行原始方法 */ protected boolean beforeinvoke(object receiver, method method, object[] args) throws throwable { return false; } protected void afterinvoke(object receiver, method method, object[] args, object invokeresult) throws throwable { } public boolean isfakedresult() { return musefakedresult; } public object getfakedresult() { return mfakedresult; } }
abstract class binderhook extends hook implements invocationhandler { private object moldobj; public binderhook(context hostcontext) { super(hostcontext); } @override public object invoke(object proxy, method method, object[] args) throws throwable { try { if (!isenable()) {//如果不能hook,执行原方法 return method.invoke(moldobj, args); } hookedmethodhandler hookedmethodhandler = mhookhandles.gethookedmethodhandler(method); if (hookedmethodhandler != null) { return hookedmethodhandler.dohookinner(moldobj, method, args); } else { return method.invoke(moldobj, args); } } catch (invocationtargetexception e) { throwable cause = e.gettargetexception(); if (cause != null && myproxy.ismethoddeclaredthrowable(method, cause)) { throw cause; } else if (cause != null) { runtimeexception runtimeexception = !textutils.isempty(cause.getmessage()) ? new runtimeexception(cause.getmessage()) : new runtimeexception(); runtimeexception.initcause(cause); throw runtimeexception; } else { runtimeexception runtimeexception = !textutils.isempty(e.getmessage()) ? new runtimeexception(e.getmessage()) : new runtimeexception(); runtimeexception.initcause(e); throw runtimeexception; } } catch (illegalargumentexception e) { try { stringbuilder sb = new stringbuilder(); sb.append(" droidplugin{"); if (method != null) { sb.append("method[").append(method.tostring()).append("]"); } else { sb.append("method[").append("null").append("]"); } if (args != null) { sb.append("args[").append(arrays.tostring(args)).append("]"); } else { sb.append("args[").append("null").append("]"); } sb.append("}"); string message = e.getmessage() + sb.tostring(); throw new illegalargumentexception(message, e); } catch (throwable e1) { throw e; } } catch (throwable e) { if (myproxy.ismethoddeclaredthrowable(method, e)) { throw e; } else { runtimeexception runtimeexception = !textutils.isempty(e.getmessage()) ? new runtimeexception(e.getmessage()) : new runtimeexception(); runtimeexception.initcause(e); throw runtimeexception; } } } abstract object getoldobj() throws exception; void setoldobj(object moldobj) { this.moldobj = moldobj; } public abstract string getservicename();//具体hook哪一个service /** * 先调用servicemanagercachebinderhook的oninstall()方法更新一下service cache * 然后生成一个新的代理对象放到mproxiedobjcache里。这样下次不管是从cache里取,还是直接通过binder调用,就都会返回我们的代理对象。 * **/ @override protected void oninstall(classloader classloader) throws throwable { new servicemanagercachebinderhook(mhostcontext, getservicename()).oninstall(classloader); moldobj = getoldobj(); class<?> clazz = moldobj.getclass();//得到class list<class<?>> interfaces = utils.getallinterfaces(clazz); class[] ifs = interfaces != null && interfaces.size() > 0 ? interfaces.toarray(new class[interfaces.size()]) : new class[0]; //用原始对象的classloader传入动态代理,得到代理对象 object proxiedobj = myproxy.newproxyinstance(clazz.getclassloader(), ifs, this); myservicemanager.addproxiedobj(getservicename(), proxiedobj); } }
结论就是读取插件apk,和宿主的uid对比,然后进行包替换,在利用binder代理hook,启动插件,这概括很是大概,不过涉及太复杂
然后是使用了,结束和使用都很多资料,很详细,不过自己研究了一翻记录下心得,也能加深理解和印象
public class mainactivity extends appcompatactivity { private string filepath = null, packagename = "cn.liuzhen.plugin"; private textview tv_val; private context context; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); context = mainactivity.this; tv_val = (textview)findviewbyid(r.id.tv_val); filepath = environment.getexternalstoragedirectory().getabsolutepath().concat("/test.apk"); } public void click(view view) { if (filepath == null){ toast.maketext(context,"filepath is null",toast.length_short).show(); return; } string result = null; int code = -1; try { switch (view.getid()) { case r.id.btn_install: code = pluginmanager.getinstance().installpackage(filepath, packagemanagercompat.install_replace_existing); result = "install"; switch (code) { case pluginmanager.install_failed_no_requestedpermission: result = "安装失败,文件请求的权限太多"; break; case packagemanagercompat.install_failed_not_support_abi: result = "宿主不支持插件的abi环境,可能宿主运行时为64位,但插件只支持32位"; break; case packagemanagercompat.install_succeeded: result = "安装完成"; break; } break; case r.id.btn_del: pluginmanager.getinstance().deletepackage(packagename, 0); result = "del"; break; case r.id.btn_open: packagemanager pm = getpackagemanager(); intent intent = pm.getlaunchintentforpackage("cn.liuzhen.plugin"); if (intent == null){ result = "intent is null"; }else startactivity(intent); break; } } catch (remoteexception e) { result = "安装失败 "+e.getmessage(); } tv_val.settext(result); } }
运行程序成功,然后把运行的apk复制一份,我上面的名称是写死的,test.apk,然后放在根目录,点击安装,显示成功后在点击打开,就能见到跳转到插件界面了,插件化通了。
接下来就是看自己怎么设计和开发了,什么东西也不能随便使用,得好好考虑,个人觉得插件化不宜大范围使用,适合小菜单的集成,毕竟都是反射的,而且还得考虑好安全问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 简单实现android短信发送器
下一篇: HTML 超链接(链接)