主目錄見:Android高級進(jìn)階知識(這是總目錄索引)
框架地址:VirtualApk
在線源碼查看:AndroidXRef
關(guān)于滴滴插件化框架VirtualApk我們已經(jīng)講了有幾篇了:
1)插件化框架VirtualApk之初始化
2)插件化框架VirtualApk之插件加載
3)插件化框架VirtualApk之Activity啟動
這篇我們緊接著前面開始講犀概,我們知道啟動服務(wù)有兩種方式startService和bindService兩種方式停团,我們前面已經(jīng)講過startService的流程分析和bindService方式的從framework分析AIDL生成文件,而且我們知道鞭呕,Service
的生命周期是我們可以手動控制的臣樱,我們可以不像Activity
生命周期的控制一樣交給系統(tǒng)管理拧廊,我們可以更簡單地控制Service
的生命周期课兄。
我們看到Service的生命周期是比較簡單的框沟,而且圖中已經(jīng)說明了startService的時候藏古,會調(diào)用onCreate()增炭,onSstartCommand()方法,然后停止服務(wù)的時候我們可以調(diào)用stopService()或者stopSelf()方法拧晕;如果是bindService的時候隙姿,則會調(diào)用onCreate(),onBind()方法返回binder對象厂捞,然后會回調(diào)ServiceConnection
對象输玷,解除綁定的時候可以調(diào)用unBindService()來回調(diào)onUnbind()方法。和上一篇一樣靡馁,我們這里就貼一下startService的啟動過程概圖:
我們看到和Activity啟動不一樣的是欲鹏,這里并不是通過
Instrumentation
來進(jìn)行管理創(chuàng)建過程的,而是直接通過ActivityManagerProxy
和AMS
通訊進(jìn)行創(chuàng)建的臭墨。
一.Service管理過程分析
插件化框架VirtualApk在Service的管理上采用了一種稱為代理分發(fā)的方式赔嚎。首先會在AndroidManifest.xml
中注冊兩種代理Service
,這樣要啟動插件Service
的時候裙犹,我們都會啟動這個代理Srevice
尽狠,然后在onStartCommand()
方法中進(jìn)行分發(fā)執(zhí)行插件的onStartCommand()
方法。所以我們先來看看這兩個代理Service的注冊情況:
<!-- Local Service running in main process -->
<service android:name="com.didi.virtualapk.delegate.LocalService" />
<!-- Daemon Service running in child process -->
<service android:name="com.didi.virtualapk.delegate.RemoteService" android:process=":daemon">
<intent-filter>
<action android:name="${applicationId}.intent.ACTION_DAEMON_SERVICE" />
</intent-filter>
</service>
我們看到這里注冊了兩個代理服務(wù)叶圃,一個是在主進(jìn)程中的袄膏,一個是在非主進(jìn)程中的,根據(jù)插件服務(wù)在的進(jìn)程進(jìn)行分別地啟動掺冠。而且在前面的初始化我們已經(jīng)看到沉馆,一個是hook 了Instrumentation
類還有一個是hook了IActivityManager
,我們來看看:
private void hookSystemServices() {
try {
Singleton<IActivityManager> defaultSingleton = (Singleton<IActivityManager>) ReflectUtil.getField(ActivityManagerNative.class, null, "gDefault");
IActivityManager activityManagerProxy = ActivityManagerProxy.newInstance(this, defaultSingleton.get());
// Hook IActivityManager from ActivityManagerNative
ReflectUtil.setField(defaultSingleton.getClass().getSuperclass(), defaultSingleton, "mInstance", activityManagerProxy);
if (defaultSingleton.get() == activityManagerProxy) {
this.mActivityManager = activityManagerProxy;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void hookAMSForO() {
try {
Singleton<IActivityManager> defaultSingleton = (Singleton<IActivityManager>) ReflectUtil.getField(ActivityManager.class, null, "IActivityManagerSingleton");
IActivityManager activityManagerProxy = ActivityManagerProxy.newInstance(this, defaultSingleton.get());
ReflectUtil.setField(defaultSingleton.getClass().getSuperclass(), defaultSingleton, "mInstance", activityManagerProxy);
} catch (Exception e) {
e.printStackTrace();
}
}
我們看到根據(jù)不同android版本分別采用了不同的方式德崭,但是最終都是通過動態(tài)代理的方式將ActivityManagerProxy
代理成我們自己的ActivityManagerProxy
對象斥黑。這樣在調(diào)用AMS的時候,我們會走到自己的ActivityManagerProxy
對象的invoke()
方法來眉厨。我們來看看invoke()
方法:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("startService".equals(method.getName())) {
try {
return startService(proxy, method, args);
} catch (Throwable e) {
Log.e(TAG, "Start service error", e);
}
} else if ("stopService".equals(method.getName())) {
try {
return stopService(proxy, method, args);
} catch (Throwable e) {
Log.e(TAG, "Stop Service error", e);
}
} else if ("stopServiceToken".equals(method.getName())) {
try {
return stopServiceToken(proxy, method, args);
} catch (Throwable e) {
Log.e(TAG, "Stop service token error", e);
}
} else if ("bindService".equals(method.getName())) {
try {
return bindService(proxy, method, args);
} catch (Throwable e) {
e.printStackTrace();
}
} else if ("unbindService".equals(method.getName())) {
try {
return unbindService(proxy, method, args);
} catch (Throwable e) {
e.printStackTrace();
}
} else if ("getIntentSender".equals(method.getName())) {
try {
getIntentSender(method, args);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("overridePendingTransition".equals(method.getName())){
try {
overridePendingTransition(method, args);
} catch (Exception e){
e.printStackTrace();
}
}
try {
// sometimes system binder has problems.
return method.invoke(this.mActivityManager, args);
} catch (Throwable th) {
Throwable c = th.getCause();
if (c != null && c instanceof DeadObjectException) {
// retry connect to system binder
IBinder ams = ServiceManager.getService(Context.ACTIVITY_SERVICE);
if (ams != null) {
IActivityManager am = ActivityManagerNative.asInterface(ams);
mActivityManager = am;
}
}
Throwable cause = th;
do {
if (cause instanceof RemoteException) {
throw cause;
}
} while ((cause = cause.getCause()) != null);
throw c != null ? c : th;
}
}
這個方法很簡單锌奴,我們看到關(guān)于Service的所有操作都被攔截了,我們這里一個一個方法來講憾股,首先我們看看startService()
方法鹿蜀。
1.startService
private Object startService(Object proxy, Method method, Object[] args) throws Throwable {
IApplicationThread appThread = (IApplicationThread) args[0];
Intent target = (Intent) args[1];
ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0);
if (null == resolveInfo || null == resolveInfo.serviceInfo) {
// is host service
return method.invoke(this.mActivityManager, args);
}
return startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_START_SERVICE);
}
我們看到這里的resolveService()
方法跟Activity啟動管理里面的resolveActivity()
方法類似,是根據(jù)intent的信息然后查找出來匹配的Service
的ResolveInfo
信息來服球,然后判斷ResolveInfo
如果為空則說明是宿主程序中的服務(wù)茴恰,否則會調(diào)用startDelegateServiceForTarget()
方法進(jìn)行處理:
private ComponentName startDelegateServiceForTarget(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) {
Intent wrapperIntent = wrapperTargetIntent(target, serviceInfo, extras, command);
return mPluginManager.getHostContext().startService(wrapperIntent);
}
我們看到這里會先調(diào)用wrapperTargetIntent()
進(jìn)行將要啟動插件的服務(wù)替換成前面提前注冊好的服務(wù),然后啟動斩熊。我們看看這里的替換代碼:
private Intent wrapperTargetIntent(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) {
// fill in service with ComponentName
target.setComponent(new ComponentName(serviceInfo.packageName, serviceInfo.name));
String pluginLocation = mPluginManager.getLoadedPlugin(target.getComponent()).getLocation();
// start delegate service to run plugin service inside
boolean local = PluginUtil.isLocalService(serviceInfo);
Class<? extends Service> delegate = local ? LocalService.class : RemoteService.class;
Intent intent = new Intent();
intent.setClass(mPluginManager.getHostContext(), delegate);
intent.putExtra(RemoteService.EXTRA_TARGET, target);
intent.putExtra(RemoteService.EXTRA_COMMAND, command);
intent.putExtra(RemoteService.EXTRA_PLUGIN_LOCATION, pluginLocation);
if (extras != null) {
intent.putExtras(extras);
}
return intent;
}
我們看到這里的首先設(shè)置intent的Component為插件中服務(wù)的Component,然后獲取插件的位置往枣,而且判斷是不是要啟動的插件服務(wù)是在獨立的進(jìn)程中,接著就設(shè)置intent的class等等一些信息。最后將提前注冊好的Service啟動分冈。到這里我們的LocalService
和RemoteService
就已經(jīng)啟動了圾另,這里的RemoteService
是繼承LocalService
的,多了一步創(chuàng)建Application的操作丈秩。我們看前面的Service的生命周期可以知道盯捌,啟動Service的過程中,會回調(diào)onStartCommand()
方法蘑秽,所以我們在這里面做相應(yīng)的操作即可,首先我們來看啟動服務(wù)的回調(diào):
case EXTRA_COMMAND_START_SERVICE: {
ActivityThread mainThread = (ActivityThread)ReflectUtil.getActivityThread(getBaseContext());
IApplicationThread appThread = mainThread.getApplicationThread();
Service service;
if (this.mPluginManager.getComponentsHandler().isServiceAvailable(component)) {
service = this.mPluginManager.getComponentsHandler().getService(component);
} else {
try {
service = (Service) plugin.getClassLoader().loadClass(component.getClassName()).newInstance();
Application app = plugin.getApplication();
IBinder token = appThread.asBinder();
Method attach = service.getClass().getMethod("attach", Context.class, ActivityThread.class, String.class, IBinder.class, Application.class, Object.class);
IActivityManager am = mPluginManager.getActivityManager();
attach.invoke(service, plugin.getPluginContext(), mainThread, component.getClassName(), token, app, am);
service.onCreate();
this.mPluginManager.getComponentsHandler().rememberService(component, service);
} catch (Throwable t) {
return START_STICKY;
}
}
service.onStartCommand(target, 0, this.mPluginManager.getComponentsHandler().getServiceCounter(service).getAndIncrement());
break;
}
這個方法就是啟動Service的方法箫攀,首先會調(diào)用isServiceAvailable()
方法判斷服務(wù)是否已經(jīng)創(chuàng)建好緩存在mServices中了肠牲,如果有則不用重新創(chuàng)建直接獲取到Service然后調(diào)用它的onStartCommand
方法,否則就重新反射創(chuàng)建Service靴跛,調(diào)用attach()
方法缀雳,然后手動調(diào)用Service的onCreate()
方法,并將創(chuàng)建好的Service添加到緩存中梢睛。如果這塊代碼有點不懂的話那么可以認(rèn)真看framework層的代碼肥印。
2.stopService
case EXTRA_COMMAND_STOP_SERVICE: {
Service service = this.mPluginManager.getComponentsHandler().forgetService(component);
if (null != service) {
try {
service.onDestroy();
} catch (Exception e) {
Log.e(TAG, "Unable to stop service " + service + ": " + e.toString());
}
} else {
Log.i(TAG, component + " not found");
}
break;
}
我們看到停止服務(wù)比較簡單,即時移除緩存中的Service绝葡,然后執(zhí)行他的onDestroy()
方法即可深碱。
3.bindService
private Object bindService(Object proxy, Method method, Object[] args) throws Throwable {
Intent target = (Intent) args[2];
ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0);
if (null == resolveInfo || null == resolveInfo.serviceInfo) {
// is host service
return method.invoke(this.mActivityManager, args);
}
Bundle bundle = new Bundle();
PluginUtil.putBinder(bundle, "sc", (IBinder) args[4]);
startDelegateServiceForTarget(target, resolveInfo.serviceInfo, bundle, RemoteService.EXTRA_COMMAND_BIND_SERVICE);
mPluginManager.getComponentsHandler().remberIServiceConnection((IBinder) args[4], target);
return 1;
}
我們看到綁定服務(wù)這里將IBinder存入了一個Bundle
中,這個IBinder
就是我們前面分析源碼時候提及的IServiceConnection
類藏畅,然后通過startDelegateServiceForTarget()
啟動代理的Service敷硅,同樣地,最終會來到LocalService
的onStartCommand()
方法中愉阎。
case EXTRA_COMMAND_BIND_SERVICE: {
ActivityThread mainThread = (ActivityThread)ReflectUtil.getActivityThread(getBaseContext());
IApplicationThread appThread = mainThread.getApplicationThread();
Service service = null;
if (this.mPluginManager.getComponentsHandler().isServiceAvailable(component)) {
service = this.mPluginManager.getComponentsHandler().getService(component);
} else {
try {
service = (Service) plugin.getClassLoader().loadClass(component.getClassName()).newInstance();
Application app = plugin.getApplication();
IBinder token = appThread.asBinder();
Method attach = service.getClass().getMethod("attach", Context.class, ActivityThread.class, String.class, IBinder.class, Application.class, Object.class);
IActivityManager am = mPluginManager.getActivityManager();
attach.invoke(service, plugin.getPluginContext(), mainThread, component.getClassName(), token, app, am);
service.onCreate();
this.mPluginManager.getComponentsHandler().rememberService(component, service);
} catch (Throwable t) {
t.printStackTrace();
}
}
try {
IBinder binder = service.onBind(target);
IBinder serviceConnection = PluginUtil.getBinder(intent.getExtras(), "sc");
IServiceConnection iServiceConnection = IServiceConnection.Stub.asInterface(serviceConnection);
if (Build.VERSION.SDK_INT >= 26) {
ReflectUtil.invokeNoException(IServiceConnection.class, iServiceConnection, "connected",
new Class[]{ComponentName.class, IBinder.class, boolean.class},
new Object[]{component, binder, false});
} else {
iServiceConnection.connected(component, binder);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
這里的代碼也并不復(fù)雜绞蹦,主要做了幾件事,首先也是判斷緩存中有沒有創(chuàng)建好的Service榜旦,如果沒有則創(chuàng)建調(diào)用他的attach()
方法和onCreate()
方法幽七,這里還有一個不同的地方是調(diào)用Service的onBind()
方法,然后會調(diào)ServiceConnection
的connected()
方法溅呢。
4.unbindService
case EXTRA_COMMAND_UNBIND_SERVICE: {
Service service = this.mPluginManager.getComponentsHandler().forgetService(component);
if (null != service) {
try {
service.onUnbind(target);
service.onDestroy();
} catch (Exception e) {
Log.e(TAG, "Unable to unbind service " + service + ": " + e.toString());
}
} else {
Log.i(TAG, component + " not found");
}
break;
}
這個跟stopService
差不多澡屡,就是多了一個在onDestroy
前面調(diào)用了onUnbind()
方法,這樣的話藕届,Service的整個啟動挪蹭,停止,綁定休偶,解綁等都已經(jīng)完成了梁厉。
還有在invoke()
方法里面有一個stopServiceToken
方法,這個方法的調(diào)用主要是在IntentService
中的stopSelf()
方法中會調(diào)用到,最終會調(diào)用mActivityManager.stopServiceToken
方法词顾,同樣的中轉(zhuǎn)到STOP操作即可.
總結(jié):到這里Service的管理我們也已經(jīng)講完了八秃,整理來說代碼邏輯不難,細(xì)節(jié)倒是非常多的肉盹,如果想要更深入了解昔驱,建議還是要認(rèn)真看一下FrameWork的源碼,希望大家能有所收獲上忍。