很惋惜,Small
不支持Service
的插件化,可是在項目中咱們確實有這樣的需求,那麼就須要研究一下如何本身來實現Service
的插件化。在討論如何實現Service
的插件化以前,必須有三點準備:android
Service
的基本知識,包括Service
的生命週期、如何啓動和結束Service
,bindService
和startService
之間的區別和聯繫,這一部分就不過多介紹了,你們能夠看一下 Carson_Ho 大神這篇文章,介紹的很全面 Android四大組件:Service服務史上最全面解析。Service
啓動的內部原理,對源碼進行一次簡單的走讀,主要是對Service
調用者、全部者以及AMS
之間的三方通訊有一個清晰的認識,你們能夠看一下我以前寫的這篇文章 Framework 源碼解析知識梳理(5) - startService 源碼分析。Retrofit
的時候也有介紹過,Retrofit 知識梳理(2) - Retrofit 動態代理內部實現。在 插件化知識梳理(6) - Small 源碼分析之 Hook 原理 這篇文章中,咱們一塊兒學習瞭如何實現Activity
的插件化,簡單地來講,實現原理就是:git
startActivity
啓動插件Activity
後,經過替換mInstrumentation
成員變量,攔截這一啓動過程,在後臺偷偷地把startActivity
時傳入的intent
中的component
替換成爲在AndroidManifest.xml
中預先註冊的佔坑Activity
,再通知ActivityManagerService
。ActivityManagerService
完成調度後,有替換客戶端中的ActivityThread
中的mH
中的mCallback
,將佔坑的Activity
從新恢復成插件的Activity
。而Service
的插件化也能夠採用相似的方式,大致的思路以下:github
startService
啓動插件Service
時,經過攔截ActivityManagerProxy
的對應方法,將Intent
中的插件Service
類型替換成預先在AndroidManifest.xml
中預先註冊好的佔坑Service
。AMS
經過ApplicationThreadProxy
回調佔坑Service
對應的生命週期時,咱們再在佔坑Service
中的onStartCommand
中,去建立插件Service
的實例,若是是第一次建立,那麼先調用它的onCreate
方法,再調用它的onStartCommand
方法,不然,就只調用onStartCommand
方法就能夠了。stopService
中止插件Service
時,一樣經過攔截ActivityManagerProxy
的對應方法,去調用插件Service
的onDestroy
,若是此時發現沒有任何一個與佔坑Service
關聯的插件Service
運行時,那麼就能夠中止插件Service
了。傳了一個簡單的例子到倉庫,你們能夠簡單地對照着看一下,下面,咱們開始分析具體的實現。bash
初始化的過程以下所示:app
public void setup(Context context) {
try {
//1.經過反射獲取到ActivityManagerNative類。
Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative");
Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault");
gDefaultField.setAccessible(true);
Object gDefault = gDefaultField.get(activityManagerNativeClass);
//2.獲取mInstance變量。
Class<?> singleton = Class.forName("android.util.Singleton");
Field instanceField = singleton.getDeclaredField("mInstance");
instanceField.setAccessible(true);
//3.獲取原始的對象。
Object original = instanceField.get(gDefault);
//4.動態代理,用於攔截Intent。
Class<?> iActivityManager = Class.forName("android.app.IActivityManager");
Object proxy = Proxy.newProxyInstance(context.getClassLoader(), new Class[]{ iActivityManager }, new IActivityManagerInvocationHandler(original));
instanceField.set(gDefault, proxy);
//5.讀取插件當中的Service。
loadService();
//6.佔坑的Component。
mStubComponentName = new ComponentName(ServiceManagerApp.getAppContext().getPackageName(), StubService.class.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
複製代碼
這裏最主要的就是作了兩件事:框架
這裏應用到了動態代理的知識,咱們用Proxy.newProxyInstance
所建立的proxy
對象,替代了ActivityManagerNative
中的gDefault
靜態變量。在 Framework 源碼解析知識梳理(1) - 應用程序與 AMS 的通訊實現 中,咱們分析過,它實際上是一個AMS
在應用程序進程中的代理類。經過這一替換過程,那麼當調用ActivityManagerNative.getDefault()
方法時,就會先通過IActivityManagerInvocationHandler
類,咱們就能夠根據invoke
所傳入的方法名,在方法真正被調用以前插入一些本身的邏輯(也就是前文所說的,將啓動插件Service
的Intent
替換成啓動佔坑Service
的Intent
),最後纔會經過Binder
調用到達AMS
端,以此達到了「欺騙系統」的目的。ide
下面是InvocationHandler
的具體實現,構造函數中傳入的是原始的ActivityManagerProxy
對象。函數
private class IActivityManagerInvocationHandler implements InvocationHandler {
private Object mOriginal;
public IActivityManagerInvocationHandler(Object original) {
mOriginal = original;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
switch (methodName) {
case "startService":
Intent matchIntent = null;
int matchIndex = 0;
for (Object object : args) {
if (object instanceof Intent) {
matchIntent = (Intent) object;
break;
}
matchIndex++;
}
if (matchIntent != null && ServiceManager.getInstance().isPlugService(matchIntent.getComponent())) {
Intent stubIntent = new Intent(matchIntent);
stubIntent.setComponent(getStubComponentName());
stubIntent.putExtra(KEY_ORIGINAL_INTENT, matchIntent);
//將插件的Service替換成佔坑的Service。
args[matchIndex] = stubIntent;
}
break;
case "stopService":
Intent stubIntent = null;
int stubIndex = 0;
for (Object object : args) {
if (object instanceof Intent) {
stubIntent = (Intent) object;
break;
}
stubIndex++;
}
if (stubIntent != null) {
boolean destroy = onStopService(stubIntent);
if (destroy) {
//若是須要銷燬佔坑的Service,那麼就替換掉Intent進行處理。
Intent destroyIntent = new Intent(stubIntent);
destroyIntent.setComponent(getStubComponentName());
args[stubIndex] = destroyIntent;
} else {
//因爲在onStopService中已經手動調用了onDestroy,所以這裏什麼也不須要作,直接返回就能夠。
return null;
}
}
break;
default:
break;
}
Log.d("ServiceManager", "call invoke, methodName=" + method.getName());
return method.invoke(mOriginal, args);
}
}
複製代碼
先看startService
,args
參數中保存了startService
所傳入的實參,這裏面就包含了啓動插件Service
的Intent
,咱們將目標Intent
的Component
替換成爲佔坑的Component
,而後將原始的Intent
保存在KEY_ORIGINAL_INTENT
字段當中,最後,經過原始的對象調用到ActivityManagerService
端。源碼分析
這裏其實就是用到了前面介紹的DexClassLoader
的知識,詳細的能夠看一下前面的這兩篇文章 插件化知識梳理(7) - 類的動態加載入門,插件化知識梳理(8) - 類的動態加載源碼分析。 最終,咱們會將插件Service
的Class
對象保存在一個mLoadServices
的Map
當中,它的Key
就是插件Service
的包名和類名。學習
private void loadService() {
try {
//從插件中加載Service類。
File dexOutputDir = ServiceManagerApp.getAppContext().getDir("dex2", 0);
String dexPath = Environment.getExternalStorageDirectory().toString() + PLUG_SERVICE_PATH;
DexClassLoader loader = new DexClassLoader(dexPath, dexOutputDir.getAbsolutePath(), null, ServiceManagerApp.getAppContext().getClassLoader());
try {
Class clz = loader.loadClass(PLUG_SERVICE_NAME);
mLoadedServices.put(new ComponentName(PLUG_SERVICE_PKG, PLUG_SERVICE_NAME), clz);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
複製代碼
接下來,在宿主中經過下面的方式啓動插件Service
類:
public void startService(View view) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(ServiceManager.PLUG_SERVICE_PKG, ServiceManager.PLUG_SERVICE_NAME));
startService(intent);
}
複製代碼
按照前面的分析,首先會走到咱們預設的「陷阱」當中,能夠看到,這裏面的Intent
仍是插件Service
的Component
名字:
Intent
就變成了佔坑的
Service
。
若是一切正常,接下來佔坑
Service
就會啓動,依次調用它的
onCreate
和
onStartCommand
方法,咱們在
onStartCommand
中,再去回調插件
Service
對應的生命週期:
public class StubService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d("StubService", "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("StubService", "onStartCommand");
ServiceManager.getInstance().onStartCommand(intent, flags, startId);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
ServiceManager.getInstance().onDestroy();
Log.d("StubService", "onDestroy");
}
}
複製代碼
這裏,咱們取出以前保存在KEY_ORIGINAL_INTENT
中原始的Intent
,經過它找到對應插件Service
的包名和類名,以此爲key
,在mLoadedServices
中找到前面從插件apk
中加載的Service
類,並經過反射實例化該對象,若是是第一次建立,那麼先執行它的onCreate
方法,並將它保存在mAliveServices
中,以後再執行它的onStartCommand
方法。
當咱們經過stopService
方法,中止插件Service
時,也會和前面相似,先走到攔截的邏輯當中:
onStop
方法中,咱們判斷它是不是須要中止插件
Service
,若是是那麼就調用插件
Service
的
onDestory()
方法,而且判斷與佔坑
Service
相關聯的插件
Service
是否都已經結束了,若是是,那麼就返回
true
,讓佔坑
Service
也銷燬。
銷燬的時候,就是將插件
Service
的
Intent
替換成佔坑
Service
:
這時的打印爲:
以上,就是實現插件化Service
的核心思路,實現起來並不簡單,須要涉及到不少的知識,這已是插件化學習的第十篇文章了。若是你們能一路看下來,能夠發現,其實插件化並無什麼神祕的地方,若是咱們但願實現任意一個組件的插件化,無非就是如下幾點:
ActivityManagerService
的交互過程,這也是最難的地方,要花不少的時間去看源碼,並且各個版本的API
也可能有所差別。Hook
,動態代理之類的知識。掌握了以上幾點,對於市面上大廠的插件框架基本可以看懂個六七成,可是對於大多數人而言,並無這麼多的時間和條件,去分析一些細節問題。我寫的這些文章,也只能算是入門水平,和你們一塊兒學習基本的思想。真正核心的東西,仍是須要有機會能應用到生產環境中才能真正掌握。
很惋惜,我也沒有這樣的機會,感受天天工做的時間都是在調UI
、解Bug
、浪費時間,只能靠着晚上的時間,一點點摸索,寫Demo
,哎,說出來都是淚,還有半年,繼續加油吧!