360手機助手使用的 DroidPlugin,它是360手機助手團隊在Android系統上實現了一種插件機制。它可以在無需安裝、修改的情況下運行APK文件,此機制對改進大型APP的架構,實現多團隊協作開發具有一定的好處。 它是一種新的插件機制,一種免安裝的運行機制 github地址: https:/ ...
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,然後放在根目錄,點擊安裝,顯示成功後在點擊打開,就能見到跳轉到插件界面了,插件化通了
接下來就是看自己怎麼設計和開發了,什麼東西也不能隨便使用,得好好考慮,個人覺得插件化不宜大範圍使用,適合小菜單的集成,畢竟都是反射的,而且還得考慮好安全問題