深入淺出Activity插件化相關原理

在這裏插入圖片描述

轉載請標明出處:【顧林海的博客】
本篇文章已授權微信公衆號 顧林海 獨家發佈

Activity的插件化解決的一個根本性問題就是插件中的Activity並沒有在宿主的AndroidManifest.xml中進行註冊,也就是說我們需要啓動一個未註冊的Activity,因此需要對Activity的啓動過程有個瞭解。

啓動Activity時會請求AMS創建Activity,這裏的AMS指的是ActivityManagerService,AMS所屬的進程與宿主(發起者)不屬於同一個進程,AMS位於SystemServer進程中。

在這裏插入圖片描述

應用程序進程與AMS之間的通信是通過Binder來實現的,AMS要管理所有APP的啓動請求,因此我們不能在SystemServer進程中進行相應的Hook,那麼我們只能在應用進程中進行相應的Hook。

如果我們啓動一個未註冊的Activity,AMS會去檢查AndroidManifest中是否註冊了該Activity,如果未註冊會報錯。

在這裏插入圖片描述

爲了讓AMS驗證通過,需要啓動一個預先在AndroidManifest中註冊的Activity,我們稱之爲佔坑,在啓動插件Activity時替換爲佔坑Activity,達到一個欺上瞞下的作用,當AMS驗證通過之後,需要將啓動的佔坑Activity替換爲插件Activity。

在這裏插入圖片描述

總結下來Activity的插件化需要做兩件事:

  • 將請求啓動的插件Activity替換爲佔坑Activity。
  • 繞過AMS驗證後,將佔坑Activity替換爲插件Activity。

什麼時候將插件Activity替換爲佔坑Activity?又是什麼時候還原插件Activity?這需要我們對Activity的啓動流程有個相應的認識。

Hook Instrumentation

我們在Activity中調用startActivity方法如下:

    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    
        @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
           startActivityForResult(intent, -1, options);
        } else {
           startActivityForResult(intent, -1);
        }
    }

調用startActivityForResult方法:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            //Activity啓動
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

startActivityForResult方法中通過調用mInstrumentation的execStartActivity方法來啓動Activity,這個mInstrumentation是Activity的成員變量,在ActivityThread的performLaunchActivity方法中通過Activity的attach方法傳入,同時Activity的創建也是在performLaunchActivity方法中創建的,通過mInstrumentation.newActivity。

//:/frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    }
    ...
    activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
    ...
}

綜上所述Instrumentation提供了execStartActivity方法來啓動Activity,newActivity方法來創建Activity。因此,第一種方案就是用代理Instrumentation來替代Activity的Instrumentation,並在代理Instrumentation的execStartActivity方法中替換爲佔坑Activity,在newActivity方法還原插件Activity。

現在我們基於第一種方案Hook Instrumentation來實現Activity的插件化。

首先創建佔坑Activity:

public class StubActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stub);
    }
}

創建插件Activity:

public class TargetActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_target);
    }
}

並在AndroidManifest.xml中註冊佔坑Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.glh.haiproject01">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".StubActivity" />
    </application>

</manifest>

在AndroidManifest.xml中沒有註冊插件Activity,這時如果啓動插件Activity會報錯。

最後Hook Instrumentation,將ActivityThread中的成員變量Instrumentation替換成代理的Instrumentation。

創建代理Instrumentation類:

public class InstrumentationProxy extends Instrumentation {

    private Instrumentation mInstrumentation;
    private PackageManager mPackageManager;

    public InstrumentationProxy(Instrumentation instrumentation, PackageManager packageManager) {
        this.mInstrumentation = instrumentation;
        this.mPackageManager = packageManager;
    }

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

        List<ResolveInfo> resolveInfo = mPackageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        //判斷啓動的插件Activity是否在AndroidManifest.xml中註冊過
        if (null == resolveInfo || resolveInfo.size() == 0) {
            //保存目標插件
            intent.putExtra(HookHelper.REQUEST_TARGET_INTENT_NAME, intent.getComponent().getClassName());
            //設置爲佔坑Activity
            intent.setClassName(who, "com.glh.haiproject01.StubActivity");
        }

        try {
            Method execStartActivity = Instrumentation.class.getDeclaredMethod("execStartActivity",
                    Context.class, IBinder.class, IBinder.class, Activity.class,
                    Intent.class, int.class, Bundle.class);
            return (ActivityResult) execStartActivity.invoke(mInstrumentation, who, contextThread, token, target, intent, requestCode, options);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException {
        String intentName=intent.getStringExtra(HookHelper.REQUEST_TARGET_INTENT_NAME);
        if(!TextUtils.isEmpty(intentName)){
            return super.newActivity(cl,intentName,intent);
        }
        return super.newActivity(cl,className,intent);
    }

}

代理類InstrumentationProxy的execStartActivity方法先判斷插件Activity是否在AndroidManifest.xml中註冊過,如果沒有註冊過就需要替換佔坑的Activity,在newActivity方法中還原插件Activity。

代理類InstrumentationProxy寫完後,需要對ActivityThread的成員變量mInstrumentation進行替換。

public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        hookActivityThreadInstrumentation();
    }


    private void hookActivityThreadInstrumentation(){
        try {
            Class<?> activityThreadClass=Class.forName("android.app.ActivityThread");
            Field activityThreadField=activityThreadClass.getDeclaredField("sCurrentActivityThread");
            activityThreadField.setAccessible(true);
            //獲取ActivityThread對象sCurrentActivityThread
            Object activityThread=activityThreadField.get(null);

            Field instrumentationField=activityThreadClass.getDeclaredField("mInstrumentation");
            instrumentationField.setAccessible(true);
            //從sCurrentActivityThread中獲取成員變量mInstrumentation
            Instrumentation instrumentation= (Instrumentation) instrumentationField.get(activityThread);
            //創建代理對象InstrumentationProxy
            InstrumentationProxy proxy=new InstrumentationProxy(instrumentation,getPackageManager());
            //將sCurrentActivityThread中成員變量mInstrumentation替換成代理類InstrumentationProxy
            instrumentationField.set(activityThread,proxy);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

這時我們在主界面點擊跳轉插件Activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_startActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,TargetActivity.class);
                startActivity(intent);
            }
        });
    }
}

運行效果:

在這裏插入圖片描述

Hook IActivityManager

第一種方案Hook Instrumentation已經順利完成,接下來我們看第二個方案,還是看這段代碼:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            //Activity啓動
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

通過mInstrumentation的execStartActivity方法啓動Activity,在execStartActivity方法中會獲取AMS的代理,Android 7.0通過ActivityManagerNative的getDefault方法獲取一個ActivityManagerProxy,這個ActivityManagerProxy內部封裝了IBinder類型的ActivityManagerService的代理類,這樣在應用程序進程中就可以通過這個ActivityManagerProxy與SystemServer進程的ActivityManagerProxy進行通信,而在Android 8.0去除了ActivityManagerProxy這個代理類,由IActivityManager代替,這裏的IActivityManager.aidl通過AIDL工具自動生成IActivityManager.java。

Android 7.0-Activity啓動

ActivityManager是一個和AMS相關聯的類,它主要對運行中的Activity進行管理,ActivityManager中相關管理方法最終會通過ActivityManagerNative的getDefault方法來得到ActivityManagerProxy,再調用ActivityManagerProxy的相關管理方法,ActivityManagerProxy就是AMS的代理類,通過這個代理類就可以和AMS進行通信。

Android7.0的Activity啓動過程會調用Instrumentation的execStartActivity方法,代碼如下:

public ActivityResult execStartActivity(
        ...
        try {
            ...
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

在execStartActivity方法中會調用ActivityManagerNative的getDefault方法來獲取ActivityManagerProxy,ActivityManagerProxy又是AMS的代理類,這樣的話就可以通過ActivityManagerProxy向AMS發送startActivity的請求。

ActivityManagerNative的getDefault方法的代碼如下:

   private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
            IBinder b = ServiceManager.getService("activity");
            ...
            IActivityManager am = asInterface(b);
            ...
            return am;
        }
    };

    static public IActivityManager getDefault() {
        return gDefault.get();
    }

在getDefault方法中調用了gDefault的get方法,gDefault是一個單例類。通過ServiceManager的getService方法獲取一個IBinder類型的AMS的引用,再將它通過asInterface方法轉換成ActivityManagerProxy類型的對象。

asInterface方法:

static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        //檢查本地進程是否有IActivityManager接口的實現
        IActivityManager in =
            (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        //本地進程沒有IActivityManager接口的實現,將IBinder類型的AMS引用封裝成AMP
        return new ActivityManagerProxy(obj);
    }

在asInterface方法中分兩種情況,首先會檢查本地進程是否有IActivityManager接口的實現,如果有就直接返回;如果沒有,就將IBinder類型的AMS引用封裝成ActivityManagerProxy。

public abstract class ActivityManagerNative extends Binder implements IActivityManager{
    ...
    class ActivityManagerProxy implements IActivityManager{
        public ActivityManagerProxy(IBinder remote){
            mRemote = remote;
        }
                ...
    }
    ...
}

ActivityManagerProxy是ActivityManagerNative的內部類,在ActivityManagerProxy的構造方法中將AMS的引用賦值給變量mRemote,這樣在ActivityManagerProxy中就可以使用AMS了。

繼續回到Instrumentation的execStartActivity方法,代碼如下:

public ActivityResult execStartActivity(
        ...
        try {
            ...
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

通過ActivityManagerNative的getDefault方法獲取AMS的代理類ActivityManagerProxy,再調用ActivityManagerProxy的startActivity方法。

ActivityManagerProxy的startActivity方法:

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        ...
        //向AMS發送START_ACTIVITY_TRANSACTION類型的進程間通信請求
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }

在ActivityManagerProxy的startActivity方法中,通過mRemote,也就是AMS的引用,向服務端的AMS發送一個START_ACTIVITY_TRANSACTION類型的進程間通信請求,服務端AMS就會從Binder線程池中讀取客戶端發來的數據,最終會調用ActivityManagerNative的onTransact方法。

@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
    switch (code) {
        case START_ACTIVITY_TRANSACTION:{
            ...
            int result = startActivity(app, callingPackage, intent, resolvedType,
            ...
            return true;
        }
        ...
    }

    return super.onTransact(code, data, reply, flags);
}

同時ActivityManagerService繼承自ActivityManagerNative,因此onTransact方法的switch語句的START_ACTIVITY_TRANSACTION分支會調用AMS的startActivity。

public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

    @Override    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
           int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
      }
}
Android 8.0-Activity啓動

Android8.0和7.0的Activity啓動過程都會調用Instrumentation的execStartActivity方法,代碼如下:

    public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, String target,
        Intent intent, int requestCode, Bundle options) {
        ...
        try {
            ...
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

在execStartActivity方法中通過ActivityManager的getService獲取IActivityManager對象,並通過IActivityManager對象的startActivity方法通知AMS啓動Activity。

public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };

IActivityManagerSingleto是一個單例類,在它的create方法中獲取iBinder類型的AMS引用,接着通過AIDL,將AMS應用轉換成IActivityManager類型的對象。相比於Android 7.0來說,這裏去掉了ActivityManagerProxy這個代理類,由IActivityManager代替,這裏的IActivityManager.aidl通過AIDL工具自動生成IActivityManager.java。

通過Android 7.0和Android 8.0的Activity啓動流程可以得出Activity插件化的另一種方案:Hook IActivityManager,通過動態代理實現。

首先創建佔坑Activity:

public class StubActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stub);
    }
}

創建插件Activity:

public class TargetActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_target);
    }
}

並在AndroidManifest.xml中註冊佔坑Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.glh.haiproject01">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".StubActivity" />
    </application>

</manifest>

在AndroidManifest.xml中沒有註冊插件Activity,這時如果啓動插件Activity會報錯。

接着開始Hook IActivityManager,創建代理類IActivityManagerProxy:

public class IActivityManagerProxy implements InvocationHandler {

    private Object mActivityManager;

    public IActivityManagerProxy(Object activityManager){
        this.mActivityManager=activityManager;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if("startActivity".equals(method.getName())){
            //攔截startActivity
            Intent intent=null;
            int index=0;
            for(int i=0,length=args.length;i<length;i++){
                if(args[i] instanceof Intent){
                    index=i;
                    break;
                }
            }
            //獲取插件Activity的Intent
            intent= (Intent) args[index];
            //創建佔坑Activity的Intent
            Intent subIntent=new Intent();
            subIntent.setClassName("com.glh.haiproject01","com.glh.haiproject01.StubActivity");
            //保存插件Activity的Intent
            subIntent.putExtra(HookHelper.REQUEST_TARGET_INTENT_NAME,intent);
            //替換爲佔坑Activity
            args[index]=subIntent;
        }
        return method.invoke(mActivityManager,args);
    }
}

IActivityManagerProxy代理類的invoke非常簡單,就是將插件Activity的Intent替換爲佔坑Activity的Intent,並保存插件Activity的Intent,方便後續還原。

    private void hookIActivityManager(){
        Object defaultSingleton;
        if(Build.VERSION.SDK_INT==26){
            //Android 8.0
            defaultSingleton=getIActivityManagerSingleton();
        }else{
            defaultSingleton=getDefault();
        }
        try {
            Class<?> singletonClazz=Class.forName("android.util.Singleton");
            Field instanceField=singletonClazz.getDeclaredField("mInstance");
            instanceField.setAccessible(true);
            //獲取defaultSingleton中IActivityManager類型的mInstance成員變量
            Object iActivityManager=instanceField.get(defaultSingleton);

            Class<?> iActivityManagerClazz=Class.forName("android.app.IActivityManager");
            Object proxy=Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[]{iActivityManagerClazz},new IActivityManagerProxy(iActivityManager));
            //替換爲代理類IActivityManagerProxy
            instanceField.set(defaultSingleton,proxy);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private Object getIActivityManagerSingleton(){
        try {
            Class<?> activityManagerClazz=Class.forName("android.app.ActivityManager");
            Field field=activityManagerClazz.getDeclaredField("IActivityManagerSingleton");
            field.setAccessible(true);
            return field.get(null);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Object getDefault(){
        try {
            Class<?> activityManagerClazz=Class.forName("android.app.ActivityManagerNative");
            Field field=activityManagerClazz.getDeclaredField("gDefault");
            field.setAccessible(true);
            return field.get(null);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

以上代碼主要就是將Singleton的IActivityManager類型的成員變量mInstance替換成通過動態代理對象。當我們向AMS請求啓動Activity時,會執行代理類IActivityManagerProxy的invoke方法進行狸貓換太子。

當AMS通過驗證後需要還原插件Activity的Intent,在Android 8.0和Android 7.0(其他版本源碼有可能不同)中,AMS通過Binder跨進程調用scheduleLaunchActivity,scheduleLaunchActivity方法在應用程序進程的Binder線程池中,通過mH發送LAUNCH_ACTIVITY消息(100)切換到主線程中創建並啓動Activity。

mH的類型是ActivityThread中的內部類H,H繼承自Handler並實現了handleMessage方法,在Handler源碼中,有這麼一段代碼:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

當mCallback不爲null時會調用handleMessage方法,mCallback類型是Callback接口,因此我們可以Hook Callback,用自定的Callback替換Handler的mCallback。

代理Callback:

public class CallBackProxy implements Handler.Callback {

    private Handler mHandler;

    public CallBackProxy(Handler handler){
        this.mHandler=handler;
    }

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.what==100){
            Object o=msg.obj;
            try {
                Field field=o.getClass().getDeclaredField("intent");
                field.setAccessible(true);
                //獲取佔坑Activity的Intent
                Intent intent= (Intent) field.get(o);
                //獲取之前保存的插件Activity的Intent
                Intent targetIntent=intent.getParcelableExtra(HookHelper.REQUEST_TARGET_INTENT_NAME);
                //將佔坑的Activity替換爲插件Activity
                intent.setComponent(targetIntent.getComponent());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        mHandler.handleMessage(msg);
        return true;
    }
}

將Handler的mCallback替換爲代理類CallBackProxy:

    private  void hookHandler(){
        try {
            Class<?> activityThreadClazz=Class.forName("android.app.ActivityThread");
            Field currentActivityThreadField=activityThreadClazz.getDeclaredField("sCurrentActivityThread");
            currentActivityThreadField.setAccessible(true);
            Object currentActivityThread=currentActivityThreadField.get(null);

            Field handlerField=activityThreadClazz.getDeclaredField("mH");
            handlerField.setAccessible(true);
            Handler mH= (Handler) handlerField.get(currentActivityThread);

            Field callbackField=Handler.class.getDeclaredField("mCallback");
            callbackField.setAccessible(true);
            //Handler的mCallback替換爲CallBackProxy
            callbackField.set(mH,new CallBackProxy(mH));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

至此,Hook IActivityManager方案已經完成,在主界面中啓動插件Activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_startActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,TargetActivity.class);
                startActivity(intent);
            }
        });
    }
}

運行效果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章