在上一篇Activity的插件化已经介绍了Android插件化的概念和通过Hook方案实现Activity的插件化。本文接着上文,介绍四大组件中另一个重要成员——Service的插件化。
Service的插件化
Service插件化的原理和Activity插件化的原理有些不同,主要是因为两者的启动过程上的差异。以Activity的StartService方法为例,其内部会调用mBase也就是ContextImpl的startService方法。用两张图来简单了解下Service的启动过程:
需要提示的是,以上对Service启动过程的分析图示是基于Android 7.0的源码
首先我们需要了解,在插件化方面Service和Activity有何不同:
- Activity是基于栈管理的,一个栈中的Activity数量不会太多,因此插件化框架处理的插件Activity数量是有限的,可以声明有限的占坑Activity来实现。但Service不同,除去硬件和系统限制,插件化框架处理的插件Service的数量可以是无限的,无法用有限的占坑Service来实现。
- 在Standard模式下多次启动同一个占坑Activity可以创建多个Actvity实例,但是多次启动同一个占坑的Service并不会创建多个Service实例。
- 用户和界面的交互会影响到Activity的生命周期,所以插件Activity的生命周期需要交由系统管理。Hook IActivityManager方案中在ActivityThread的实际创建和启动Activity流程(调用handleLaunchActivity方法)开始之前,还原插件Activity就是为了这一点。而Service的生命周期不受用户影响,可以由开发者管理生命周期,没有必要还原插件。
综合以上三点区别,Service的插件化不能用Hook IActivityManager方案来实现。
代理分发实现
Activity插件化的重点在于要保证它的生命周期交由系统管理,而Service插件化的重点是保证它的优先级,这就需要用一个真正的Service来实现,而不是像占坑的Activity那样起到一个占坑的作用,实际上并没有真的被启动。当启动插件Service时,就需要先启动代理Service,这个代理Service运行起来之后,在它的onStartCommand等方法中进行分发,创建插件Service的实例,执行它的onCreate和onStartCommand方法。这一方案就是代理分发。下面通过代码演示:
首先用TargetService表示插件Service,这里省略了插件Service的加载逻辑。代码如下
public class TargetService extends Service {
private final static String TAG = "TargetService";
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG,"onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
这里只是用来打印Log,来证明TargetService已启动。TargetService代表插件Service,没有在AndroidManifest.xml中注册,直接启动无法通过AMS的校验,需要先启动代理Service,为了达到这一目的,我们需要Hook IActivityManager,具体的原理和前文Activity的插件化中提到的类似,定义IActivityManagerProxy替换单例模式的IActivityManager。代码如下
public class IActivityManagerProxy implements InvocationHandler {
private final static String TAG = "IActivityManagerProxy";
private Object iActivityManager;
public IActivityManagerProxy(Object iActivityManager){
this.iActivityManager = iActivityManager;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("startService")){
Intent intent = null;
int index = 0;
for(int i = 0; i
简单来说就是对iActivityManager的startService进行拦截,判断如果启动的是TargetService,就用代理ProxyService来替换。接下来就是定义ProxyService。首先要在AndroidManifest.xml中注册代理Service,代码如下:
接着看ProxyService的实现
public class ProxyService extends Service {
private final static String TAG = "ProxyService";
public final static String TARGET_SERVICE = "TargetService";
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG,"onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"onStartCommand");
if(intent == null || !intent.hasExtra(TARGET_SERVICE)){
return START_STICKY;
}
String targetServiceName = intent.getStringExtra(TARGET_SERVICE);
Log.e(TAG,"targetServiceName = " + targetServiceName);
if(targetServiceName == null){
return START_STICKY;
}
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Method getApplicationThreadMethod =
activityThreadClass.getDeclaredMethod("getApplicationThread");
getApplicationThreadMethod.setAccessible(true);
Field sCurrentActivityThreadField =
activityThreadClass.getDeclaredField("sCurrentActivityThread");
sCurrentActivityThreadField.setAccessible(true);
Object sCurrentActivityThread = sCurrentActivityThreadField.get(activityThreadClass);
Object applicationThread = getApplicationThreadMethod.invoke(sCurrentActivityThread);
Class iInterfaceClass = Class.forName("android.os.IInterface");
Method asbinderMethod = iInterfaceClass.getDeclaredMethod("asBinder");
asbinderMethod.setAccessible(true);
Object token = asbinderMethod.invoke(applicationThread);
Class serviceClass = Class.forName("android.app.Service");
Method attachMethod = serviceClass.getDeclaredMethod("attach",
Context.class,activityThreadClass,String.class,IBinder.class, Application.class,Object.class);
attachMethod.setAccessible(true);
Object defaultSingleton = null;
if(Build.VERSION.SDK_INT >= 26){
Class activityManagerClass = Class.forName("android.app.ActivityManager");
Field activityManagerSinletonField = activityManagerClass.getDeclaredField("IActivityManagerSingleton");
activityManagerSinletonField.setAccessible(true);
defaultSingleton = activityManagerSinletonField.get(activityManagerClass);
} else {
Class activityManagerClass = Class.forName("android.app.ActivityManagerNative");
Field activityManagerSinletonField = activityManagerClass.getDeclaredField("gDefault");
activityManagerSinletonField.setAccessible(true);
defaultSingleton = activityManagerSinletonField.get(activityManagerClass);
}
Class singletonClass = Class.forName("android.util.Singleton");
Field mInstanceField = singletonClass.getDeclaredField("mInstance");
mInstanceField.setAccessible(true);
Object iActivityManager = mInstanceField.get(defaultSingleton);
Service TargetService = (Service)Class.forName(targetServiceName).newInstance();
attachMethod.invoke(TargetService,this,sCurrentActivityThread,
targetServiceName, token,getApplication(),iActivityManager);
TargetService.onCreate();
TargetService.onStartCommand(intent,flags,startId);
} catch (Exception e) {
e.printStackTrace();
return START_STICKY;
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
在onStartCommand方法中进行分发,其中主要做了三件事:
- ProxyService需要长时间对Service进行分发处理,所以在参数条件不满足、出现异常和代码执行完毕时需要返回START_STICKY,这样ProxyService会被重新创建并执行onStartCommand方法。
- 创建TargetService的实例并通过反射调用TargetService实例的attach方法
- 进行代理分发,执行TargetService实例的onCreate方法和onStartCommand方法
其中因为调用Service的attach方法需要ActivityThread、IBinder、Application等参数,所以除了需要通过反射获取attach方法外,还需要获取相应的参数。对这段代码不熟悉的同学,可以看看ActivityThread的handleCreateService方法的相关源码,这里就不多说了。
接下来需要做的就是,用我们定义的IActivityManagerProxy替换IActivityManager,这里我选择在Application的onCreate方法中执行替换,代码如下:
public class TestApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
try {
initHook();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initHook() throws Exception {
Object defaultSingleton = null;
if(Build.VERSION.SDK_INT >= 26) {
Class activityManagerClass = Class.forName("android.app.ActivityManager");
Field songletonField = activityManagerClass.getDeclaredField("IActivityManagerSingleton");
songletonField.setAccessible(true);
defaultSingleton = songletonField.get(activityManagerClass);
}else{
Class activityManagerClass = Class.forName("android.app.ActivityManagerNative");
Field songletonField = activityManagerClass.getDeclaredField("gDefault");
songletonField.setAccessible(true);
defaultSingleton = songletonField.get(activityManagerClass);
}
Class singletonClass = Class.forName("android.util.Singleton");
Field mInstanceField = singletonClass.getDeclaredField("mInstance");
mInstanceField.setAccessible(true);
Class iActivityManagerClass = Class.forName("android.app.IActivityManager");
Object iActivityManager = mInstanceField.get(defaultSingleton);
Object iActivityManagerProxy = Proxy.newProxyInstance(getClassLoader(),
new Class[]{iActivityManagerClass},new IActivityManagerProxy(iActivityManager));
mInstanceField.set(defaultSingleton,iActivityManagerProxy);
}
}
代码也和Activity的插件化中讲到过的非常相似。最后就是在MainActivity中启动TargetService:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button startBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this,TargetService.class);
startService(intent);
}
}
运行项目,点击按钮,可以通过打印log看出ProxyService和TargetService都启动了。
总结
Service的插件化和Activity的插件化原理不同,不能采用Activity的插件化中提到的Hook Instrumentation和Hook IActivityManager方案。因此选择采用代理分发方案,即通过先启动代理Service,然后在其onStartCommand方法中启动插件Service,实现分发处理。