Activity插件化原理第一種方案:Hook Instrumentation

人生一切難題,知識給你答案

舒適提示:閱讀本文須要15-20分鐘(一大波代碼)
公衆號:顧林海(天天更新優質文章)php


今天,咱們來解決一個問題:java

Activity插件化原理第一種方案:Hook Instrumentationandroid

人生一切難題,知識給你答案。web


Activity的插件化解決的一個根本性問題就是插件中的Activity並無在宿主的AndroidManifest.xml中進行註冊,也就是說咱們須要啓動一個未註冊的Activity,所以須要對Activity的啓動過程有個瞭解。windows

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

未命名文件 (5).png

應用程序進程與AMS之間的通訊是經過Binder來實現的,AMS要管理全部APP的啓動請求,所以咱們不能在SystemServer進程中進行相應的Hook,那麼咱們只能在應用進程中進行相應的Hook。ide

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

未命名文件 (6).png

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

未命名文件 (8).png

總結下來Activity的插件化須要作兩件事:spa

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

何時將插件Activity替換爲佔坑Activity?又是何時還原插件Activity?這須要咱們對Activity的啓動流程有個相應的認識。

咱們在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);
            }
        });
    }
}
複製代碼

運行效果:

wq1.gif


838794-506ddad529df4cd4.webp.jpg
相關文章
相關標籤/搜索