Android Tencent Shadow 插件接入指南

| 此文寫于 2020年渗蟹,與最新版本相差甚遠(yuǎn)贮尉,請酌情觀賞

  • 撒鹽
  • 一拌滋、clone 倉庫
  • 二、測試編譯
  • 三猜谚、將Shadow庫發(fā)布到本地倉庫
  • 四败砂、宿主接入
    • 1 添加依賴
    • 2 添加代理 Activity 主題
    • 3 清單文件注冊代理Activity
    • 4 在宿主中創(chuàng)建 PluginManager 管理工具
      • a 創(chuàng)建 PluginManager文件升級器
      • b 創(chuàng)建插件進(jìn)程服務(wù)
      • c 實(shí)現(xiàn)Log工具
      • d 在 Application 創(chuàng)建 PluginManager
    • 5 宿主啟動插件Activity
    • 6 宿主混淆
  • 五、PluginManager 工程
    • 1 添加依賴
    • 2 創(chuàng)建插件管理類
    • 3 使用上面創(chuàng)建的插件管理類
    • 4 混淆
    • 5 編譯
  • 六魏铅、插件接入
    • 1 在根gradle中加入依賴
    • 2 在你原項(xiàng)目基礎(chǔ)上創(chuàng)建應(yīng)用級模塊 my-runtime
      • a 添加依賴
      • b 創(chuàng)建殼子
      • c 混淆
    • 3 在你原項(xiàng)目基礎(chǔ)上創(chuàng)建應(yīng)用級模塊 my-loader
      • a 添加依賴
      • b 實(shí)現(xiàn)插件組件管理類
      • c 創(chuàng)建插件加載器
      • d 使用插件加載器
      • e 混淆
    • 4 在你的業(yè)務(wù)應(yīng)用工程gradle中配置插件
      • a 添加依賴
      • b 在gradle最底下配置插件
    • 5 編譯
  • 七昌犹、使用幫助
    • 1 檢測當(dāng)前是否處于插件狀態(tài)下
    • 2 插件調(diào)用宿主類
    • 3 將本地倉庫發(fā)布放到 gitee 或 github
  • 持續(xù)更新

[TOC]

撒鹽

完成一個Shadow插件,項(xiàng)目需要三個工程:宿主览芳,PluginManager斜姥,插件。
http://www.reibang.com/p/f00dc837227f
Java8 系統(tǒng)環(huán)境沧竟,項(xiàng)目java8配置如下:

 compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    // work-runtime-ktx 2.1.0 and above now requires Java 8
    kotlinOptions {
        jvmTarget = "1.8"
    }

一铸敏、clone 倉庫

https://github.com/Tencent/Shadow

二、測試編譯

在 Shadow 目錄下使用命令, 確保在 Java8 環(huán)境:

./gradlew build

三悟泵、將Shadow庫發(fā)布到本地倉庫

可以先在 buildScripts/gradle/common.gradle 路徑下杈笔,修改發(fā)布版本或其他信息:

 ext.ARTIFACT_VERSION = ext.VERSION_NAME + ext.VERSION_SUFFIX
./gradlew publish

成功后,在下面目錄可找到文件:

/Users/victor/.m2/repository/com/tencent/shadow/dynamic
/Users/victor/.m2/repository/com/tencent/shadow/core
在對應(yīng)文件里可以找到相應(yīng)的版本信息糕非,至此蒙具,就可以在 Android Studio 中使用Shadow SDK了。

對應(yīng)的依賴寫法舉例:

implementation "com.tencent.shadow.dynamic:host:2.0.12-c7497f58-SNAPSHOT"

可以在根目錄配置 shadow_version 版本:

ext.shadow_version = '2.0.12-c7497f58-SNAPSHOT'

添加本地maven倉庫即可使用:

 mavenLocal()

四朽肥、宿主接入

1 添加依賴

implementation "com.tencent.shadow.dynamic:host:$shadow_version"

2 添加代理 Activity 主題

這里要求背景透明即可店量, 可根據(jù)自己需求修改,建議僅豎屏:

   <style name="PluginContainerActivity" parent="@android:style/Theme.NoTitleBar.Fullscreen">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>

3 清單文件注冊代理Activity

 <!--container 注冊
          注意configChanges需要全注冊
          theme需要注冊成透明

          這些類不打包在host中,打包在runtime中鞠呈,以便減少宿主方法數(shù)增量
          Activity 路徑需要和插件中的匹配融师,后面會說到
          -->
        <activity
            android:name="com.tencent.shadow.sample.runtime.PluginDefaultProxyActivity"
            android:launchMode="standard"
            android:screenOrientation="portrait"
            android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
            android:hardwareAccelerated="true"
            android:theme="@style/PluginContainerActivity"
            android:process=":plugin" />

        <activity
            android:name="com.tencent.shadow.sample.runtime.PluginSingleInstance1ProxyActivity"
            android:launchMode="singleInstance"
            android:screenOrientation="portrait"
            android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
            android:hardwareAccelerated="true"
            android:theme="@style/PluginContainerActivity"
            android:process=":plugin" />

        <activity
            android:name="com.tencent.shadow.sample.runtime.PluginSingleTask1ProxyActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
            android:hardwareAccelerated="true"
            android:theme="@style/PluginContainerActivity"
            android:process=":plugin" />

        <provider
            android:authorities="com.tencent.shadow.contentprovider.authority.dynamic"
            android:name="com.tencent.shadow.core.runtime.container.PluginContainerContentProvider" />
        <!--container 注冊 end -->

4 在宿主中創(chuàng)建 PluginManager 管理工具

PluginManager 用來裝載插件,是通過加載一個單獨(dú)的apk來創(chuàng)建的蚁吝。
下面會說怎么生成這個apk旱爆,先知道在宿主中怎么用即可。

a 創(chuàng)建 PluginManager文件升級器

里面的內(nèi)容根據(jù)自己的需求自行實(shí)現(xiàn):

import com.tencent.shadow.dynamic.host.PluginManagerUpdater;

import java.io.File;
import java.util.concurrent.Future;

public class FixedPathPmUpdater implements PluginManagerUpdater {

    final private File apk;

    FixedPathPmUpdater(File apk) {
        this.apk = apk;
    }

    /**
     * @return <code>true</code>表示之前更新過程中意外中斷了
     */
    @Override
    public boolean wasUpdating() {
        return false;
    }
    /**
     * 更新
     *
     * @return 當(dāng)前最新的PluginManager窘茁,可能是之前已經(jīng)返回過的文件怀伦,但它是最新的了。
     */
    @Override
    public Future<File> update() {
        return null;
    }
    /**
     * 獲取本地最新可用的
     *
     * @return <code>null</code>表示本地沒有可用的
     */
    @Override
    public File getLatest() {
        return apk;
    }
    /**
     * 查詢是否可用
     *
     * @param file PluginManagerUpdater返回的file
     * @return <code>true</code>表示可用山林,<code>false</code>表示不可用
     */
    @Override
    public Future<Boolean> isAvailable(final File file) {
        return null;
    }
}

b 創(chuàng)建插件進(jìn)程服務(wù)

import com.tencent.shadow.dynamic.host.PluginProcessService;
/**
 * 一個PluginProcessService(簡稱PPS)代表一個插件進(jìn)程房待。插件進(jìn)程由PPS啟動觸發(fā)啟動。
 * 新建PPS子類允許一個宿主中有多個互不影響的插件進(jìn)程。
 */
public class MainPluginProcessService extends PluginProcessService {
}

在清單文件注冊:

        <service
            android:name=".MainPluginProcessService"
            android:process=":plugin" />

c 實(shí)現(xiàn)Log工具

import com.tencent.shadow.core.common.ILoggerFactory;
public class AndroidLoggerFactory implements ILoggerFactory{...}

示例: https://github.com/Tencent/Shadow/blob/master/projects/sample/source/sample-host/src/main/java/com/tencent/shadow/sample/host/AndroidLogLoggerFactory.java

d 在 Application 創(chuàng)建 PluginManager

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        onApplicationCreate(this);
    }
    
    /**
     * 這個PluginManager對象在Manager升級前后是不變的桑孩。它內(nèi)部持有具體實(shí)現(xiàn)拜鹤,升級時更換具體實(shí)現(xiàn)。
     */
    private static PluginManager sPluginManager;

    public static PluginManager getPluginManager() {
        return sPluginManager;
    }

    public static void onApplicationCreate(Application application) {
        //Log接口Manager也需要使用敏簿,所以主進(jìn)程也初始化宣虾。
        LoggerFactory.setILoggerFactory(new AndroidLoggerFactory());

        if (isProcess(application, ":plugin")) {
            //在全動態(tài)架構(gòu)中,Activity組件沒有打包在宿主而是位于被動態(tài)加載的runtime绣硝,
            //為了防止插件crash后,系統(tǒng)自動恢復(fù)crash前的Activity組件握玛,此時由于沒有加載runtime而發(fā)生classNotFound異常次员,導(dǎo)致二次crash
            //因此這里恢復(fù)加載上一次的runtime
            DynamicRuntime.recoveryRuntime(application);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                WebView.setDataDirectorySuffix("plugin")
            }
        }

        FixedPathPmUpdater fixedPathPmUpdater
                = new FixedPathPmUpdater(new File("生成的PluginManager.apk文件路徑"));
        boolean needWaitingUpdate
                = fixedPathPmUpdater.wasUpdating()//之前正在更新中淑蔚,暗示更新出錯了愕撰,應(yīng)該放棄之前的緩存
                || fixedPathPmUpdater.getLatest() == null;//沒有本地緩存
        Future<File> update = fixedPathPmUpdater.update();
        if (needWaitingUpdate) {
            try {
                update.get();//這里是阻塞的刹衫,需要業(yè)務(wù)自行保證更新Manager足夠快。
            } catch (Exception e) {
                throw new RuntimeException("Sample程序不容錯", e);
            }
        }
        sPluginManager = new DynamicPluginManager(fixedPathPmUpdater);
    }

    private static boolean isProcess(Context context, String processName) {
        String currentProcName = "";
        ActivityManager manager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == myPid()) {
                currentProcName = processInfo.processName;
                break;
            }
        }

        return currentProcName.endsWith(processName);
    }
}

5 宿主啟動插件Activity

                PluginManager pluginManager = Application.getPluginManager();
                  /**
                     * @param context context
                     * @param formId  標(biāo)識本次請求的來源位置搞挣,用于區(qū)分入口
                     * @param bundle  參數(shù)列表, 建議在參數(shù)列表加入自己的驗(yàn)證
                     * @param callback 用于從PluginManager實(shí)現(xiàn)中返回View
                     */
                Bundle bundle = new Bundle()
                // 插件 zip带迟,這幾個參數(shù)也都可以不傳,直接在 PluginManager 中硬編碼 
                bundle.putString("plugin_path", "/data/local/tmp/plugin-debug.zip");
                // partKey 每個插件都有自己的 partKey 用來區(qū)分多個插件囱桨,如何配置在下面講到
                bundle.putString("part_key", "my-plugin");
                // 路徑舉例:com.google.samples.apps.sunflower.GardenActivity
                bundle.putString("activity_class_name", "啟動的插件Activity路徑");
                // 要傳入到插件里的參數(shù)
                bundle.putBundle("extra_to_plugin_bundle", new Bundle())
      
                pluginManager.enter(MainActivity.this, formId, new Bundle(), new EnterCallback() {
                    @Override
                    public void onShowLoadingView(View view) {
                    }

                    @Override
                    public void onCloseLoadingView() {

                    }

                    @Override
                    public void onEnterComplete() {
                        // 啟動成功
                    }
                });

6 宿主混淆

-keep class com.tencent.shadow.core.common.**{*;}
-keep class com.tencent.shadow.core.runtime.**{*;}
-keep class com.tencent.shadow.dynamic.host.**{*;}

五仓犬、PluginManager 工程

創(chuàng)建一個新項(xiàng)目,用來生成插件管理apk包舍肠。

1 添加依賴

    implementation "com.tencent.shadow.dynamic:manager:$shadow_version"
    compileOnly "com.tencent.shadow.core:common:$shadow_version"
    compileOnly "com.tencent.shadow.dynamic:host:$shadow_version"

2 創(chuàng)建插件管理類

下面行數(shù)有點(diǎn)多搀继,只要修改 TODO 相關(guān)方法即可:

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;

import com.tencent.shadow.core.manager.installplugin.InstalledPlugin;
import com.tencent.shadow.core.manager.installplugin.InstalledType;
import com.tencent.shadow.core.manager.installplugin.PluginConfig;
import com.tencent.shadow.dynamic.host.EnterCallback;
import com.tencent.shadow.dynamic.host.FailedException;
import com.tencent.shadow.dynamic.loader.PluginServiceConnection;
import com.tencent.shadow.dynamic.manager.PluginManagerThatUseDynamicLoader;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Afra55
 * @date 2020/5/19
 * A smile is the best business card.
 */
public class MyPluginManager extends PluginManagerThatUseDynamicLoader {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private ExecutorService mFixedPool = Executors.newFixedThreadPool(4);

    protected MyPluginManager(Context context) {
        super(context);
    }

    /**
     * TODO 下面內(nèi)容需要自己實(shí)現(xiàn)
     * @return PluginManager實(shí)現(xiàn)的別名,用于區(qū)分不同PluginManager實(shí)現(xiàn)的數(shù)據(jù)存儲路徑
     */
    @Override
    protected String getName() {
        return "sample-manager";
    }

    /**
     * TODO 下面內(nèi)容需要自己實(shí)現(xiàn)
     * @return demo插件so的abi
     */
    @Override
    public String getAbi() {
        return "";
    }

    /**
     * TODO 下面內(nèi)容需要自己實(shí)現(xiàn)
     * @return 宿主中注冊的PluginProcessService實(shí)現(xiàn)的類名
     */
    protected String getPluginProcessServiceName() {
        return "com.tencent.shadow.sample.introduce_shadow_lib.MainPluginProcessService";
    }

    /**
     * TODO 下面內(nèi)容需要自己實(shí)現(xiàn)
     * @param context context
     * @param fromId  標(biāo)識本次請求的來源位置翠语,用于區(qū)分入口
     * @param bundle  參數(shù)列表
     * @param callback 用于從PluginManager實(shí)現(xiàn)中返回View
     */
    @Override
    public void enter(final Context context, long fromId, Bundle bundle, final EnterCallback callback) {
        // 插件 zip 包地址叽躯,可以直接寫在這里,也用Bundle可以傳進(jìn)來
        final String pluginZipPath = bundle.getString("plugin_path");
        final String partKey = bundle.getString("part_key");
        final String className = bundle.getString("activity_class_name");
        if (className == null) {
            throw new NullPointerException("className == null");
        }
        if (fromId == 1011) { // 打開 Activity 示例
            final Bundle extras = bundle.getBundle("extra_to_plugin_bundle");
            if (callback != null) {
                // 開始加載插件了肌括,實(shí)現(xiàn)加載布局
                callback.onShowLoadingView(null);
            }
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        InstalledPlugin installedPlugin
                                = installPlugin(pluginZipPath, null, true);//這個調(diào)用是阻塞的
                        Intent pluginIntent = new Intent();
                        pluginIntent.setClassName(
                                context.getPackageName(),
                                className
                        );
                        if (extras != null) {
                            pluginIntent.replaceExtras(extras);
                        }

                        startPluginActivity(context, installedPlugin, partKey, pluginIntent);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    if (callback != null) {
                        Handler uiHandler = new Handler(Looper.getMainLooper());
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                // 到這里插件就啟動完成了
                                callback.onCloseLoadingView();
                                callback.onEnterComplete();
                            }
                        });
                    }
                }
            });

        } else if (fromId == 1012) { // 打開Server示例
            Intent pluginIntent = new Intent();
            pluginIntent.setClassName(context.getPackageName(), className);

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        InstalledPlugin installedPlugin
                                = installPlugin(pluginZipPath, null, true);//這個調(diào)用是阻塞的

                        loadPlugin(installedPlugin.UUID, partKey);

                        Intent pluginIntent = new Intent();
                        pluginIntent.setClassName(context.getPackageName(), className);

                        boolean callSuccess = mPluginLoader.bindPluginService(pluginIntent, new PluginServiceConnection() {
                            @Override
                            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                               // 在這里實(shí)現(xiàn)AIDL進(jìn)行通信操作
                            }

                            @Override
                            public void onServiceDisconnected(ComponentName componentName) {
                                throw new RuntimeException("onServiceDisconnected");
                            }
                        }, Service.BIND_AUTO_CREATE);

                        if (!callSuccess) {
                            throw new RuntimeException("bind service失敗 className==" + className);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        } else {
            throw new IllegalArgumentException("不認(rèn)識的fromId==" + fromId);
        }
    }



    public InstalledPlugin installPlugin(String zip, String hash , boolean odex) throws IOException, JSONException, InterruptedException, ExecutionException {
        final PluginConfig pluginConfig = installPluginFromZip(new File(zip), hash);
        final String uuid = pluginConfig.UUID;
        List<Future> futures = new LinkedList<>();
        if (pluginConfig.runTime != null && pluginConfig.pluginLoader != null) {
            Future odexRuntime = mFixedPool.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    oDexPluginLoaderOrRunTime(uuid, InstalledType.TYPE_PLUGIN_RUNTIME,
                            pluginConfig.runTime.file);
                    return null;
                }
            });
            futures.add(odexRuntime);
            Future odexLoader = mFixedPool.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    oDexPluginLoaderOrRunTime(uuid, InstalledType.TYPE_PLUGIN_LOADER,
                            pluginConfig.pluginLoader.file);
                    return null;
                }
            });
            futures.add(odexLoader);
        }
        for (Map.Entry<String, PluginConfig.PluginFileInfo> plugin : pluginConfig.plugins.entrySet()) {
            final String partKey = plugin.getKey();
            final File apkFile = plugin.getValue().file;
            Future extractSo = mFixedPool.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    extractSo(uuid, partKey, apkFile);
                    return null;
                }
            });
            futures.add(extractSo);
            if (odex) {
                Future odexPlugin = mFixedPool.submit(new Callable() {
                    @Override
                    public Object call() throws Exception {
                        oDexPlugin(uuid, partKey, apkFile);
                        return null;
                    }
                });
                futures.add(odexPlugin);
            }
        }

        for (Future future : futures) {
            future.get();
        }
        onInstallCompleted(pluginConfig);

        return getInstalledPlugins(1).get(0);
    }


    public void startPluginActivity(Context context, InstalledPlugin installedPlugin, String partKey, Intent pluginIntent) throws RemoteException, TimeoutException, FailedException {
        Intent intent = convertActivityIntent(installedPlugin, partKey, pluginIntent);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public Intent convertActivityIntent(InstalledPlugin installedPlugin, String partKey, Intent pluginIntent) throws RemoteException, TimeoutException, FailedException {
        loadPlugin(installedPlugin.UUID, partKey);
        return mPluginLoader.convertActivityIntent(pluginIntent);
    }

    private void loadPluginLoaderAndRuntime(String uuid) throws RemoteException, TimeoutException, FailedException {
        if (mPpsController == null) {
            bindPluginProcessService(getPluginProcessServiceName());
            waitServiceConnected(10, TimeUnit.SECONDS);
        }
        loadRunTime(uuid);
        loadPluginLoader(uuid);
    }

    protected void loadPlugin(String uuid, String partKey) throws RemoteException, TimeoutException, FailedException {
        loadPluginLoaderAndRuntime(uuid);
        Map map = mPluginLoader.getLoadedPlugin();
        if (!map.containsKey(partKey)) {
            mPluginLoader.loadPlugin(partKey);
        }
        Boolean isCall = (Boolean) map.get(partKey);
        if (isCall == null || !isCall) {
            mPluginLoader.callApplicationOnCreate(partKey);
        }
    }
}

3 使用上面創(chuàng)建的插件管理類

創(chuàng)建路徑:com.tencent.shadow.dynamic.impl, 在該路徑下創(chuàng)建兩個文件:

package com.tencent.shadow.dynamic.impl;

import android.content.Context;

import com.tencent.shadow.dynamic.host.ManagerFactory;
import com.tencent.shadow.dynamic.host.PluginManagerImpl;
import com.tencent.shadow.sample.manager.MyPluginManager;

/**
 * 此類包名及類名固定
 */
public final class ManagerFactoryImpl implements ManagerFactory {
    @Override
    public PluginManagerImpl buildManager(Context context) {
        return new MyPluginManager(context);
    }
}

/**
 * 此類包名及類名固定
 * classLoader的白名單
 * PluginManager可以加載宿主中位于白名單內(nèi)的類
 */
public interface WhiteList {
    String[] sWhiteList = new String[]
            {
            };
}

4 混淆

-keep class com.tencent.shadow.dynamic.impl.**{*;}
-keep class com.tencent.shadow.dynamic.loader.**{*;}
-keep class com.tencent.shadow.dynamic.impl.ManagerFactoryImpl {*;}
-keep class com.tencent.shadow.dynamic.impl.WhiteList {*;}

5 編譯

使用命令点骑,或者在Gradle 工具窗口點(diǎn)擊 assembleDebug:

./gradlew assembleDebug

生成apk路徑:
sample-manager/build/outputs/apk/debug/sample-manager-debug.apk

至此,插件管理工程完成。

六黑滴、插件接入

插件的包名和宿主的包名要保持一致憨募。

1 在根gradle中加入依賴

classpath "com.tencent.shadow.core:gradle-plugin:$shadow_version"

2 在你原項(xiàng)目基礎(chǔ)上創(chuàng)建應(yīng)用級模塊 my-runtime

這個應(yīng)用模塊主要放在宿主中注冊的殼子,路徑名和類名要一致跷跪。
這個模塊的 applicationId 可以隨意葛菇。

a 添加依賴

這個應(yīng)用模塊只需要下面的依賴眯停,其他依賴都能刪掉卿泽,清單文件也不需要任何配置签夭,生成項(xiàng)目時自動創(chuàng)建的Activity 都可以刪掉第租。

  implementation "com.tencent.shadow.core:activity-container:$shadow_version"

b 創(chuàng)建殼子

殼子路徑包名和宿主中注冊的要保持一致:

package com.tencent.shadow.sample.runtime;
import com.tencent.shadow.core.runtime.container.PluginContainerActivity;
public class PluginDefaultProxyActivity extends PluginContainerActivity {
}
package com.tencent.shadow.sample.runtime;
import com.tencent.shadow.core.runtime.container.PluginContainerActivity;
public class PluginSingleInstance1ProxyActivity extends PluginContainerActivity {
}
package com.tencent.shadow.sample.runtime;
import com.tencent.shadow.core.runtime.container.PluginContainerActivity;
public class PluginSingleTask1ProxyActivity extends PluginContainerActivity {
}

c 混淆

-keep class org.slf4j.**{*;}
-dontwarn org.slf4j.impl.**

-keep class com.tencent.shadow.core.runtime.**{*;}
#需要keep在宿主AndroidManifest.xml注冊的殼子activity
-keep class com.tencent.shadow.sample.runtime.**{*;}

3 在你原項(xiàng)目基礎(chǔ)上創(chuàng)建應(yīng)用級模塊 my-loader

這個應(yīng)用模塊主要定義插件組件和殼子代理組件的配對關(guān)系丐吓,manager在加載"插件"時券犁,首先需要先加載"插件"中的runtime和loader粘衬, 再通過loader的Binder(插件應(yīng)該處于獨(dú)立進(jìn)程中避免native庫沖突)操作loader進(jìn)而加載業(yè)務(wù)App。

這個模塊的 applicationId 可以隨意等缀。

a 添加依賴

這個應(yīng)用模塊只需要下面的依賴尺迂,其他依賴都能刪掉,清單文件也不需要任何配置股毫,生成項(xiàng)目時自動創(chuàng)建的Activity 都可以刪掉铃诬。

    implementation "com.tencent.shadow.dynamic:loader-impl:$shadow_version"

    compileOnly "com.tencent.shadow.core:activity-container:$shadow_version"
    compileOnly "com.tencent.shadow.core:common:$shadow_version"
    //下面這行依賴是為了防止在proguard的時候找不到LoaderFactory接口
    compileOnly "com.tencent.shadow.dynamic:host:$shadow_version"

b 實(shí)現(xiàn)插件組件管理類

import android.content.ComponentName;
import android.content.Context;
import com.tencent.shadow.core.loader.infos.ContainerProviderInfo;
import com.tencent.shadow.core.loader.managers.ComponentManager;

import java.util.ArrayList;
import java.util.List;

public class SampleComponentManager extends ComponentManager {

    /**
     * runtime 模塊中定義的殼子Activity, 路徑類名保持一致,需要在宿主AndroidManifest.xml注冊
     */
    private static final String DEFAULT_ACTIVITY = "com.tencent.shadow.sample.runtime.PluginDefaultProxyActivity";
    private static final String SINGLE_INSTANCE_ACTIVITY = "com.tencent.shadow.sample.runtime.PluginSingleInstance1ProxyActivity";
    private static final String SINGLE_TASK_ACTIVITY = "com.tencent.shadow.sample.runtime.PluginSingleTask1ProxyActivity";

    private Context context;

    public SampleComponentManager(Context context) {
        this.context = context;
    }


    /**
     * 配置插件Activity 到 殼子Activity的對應(yīng)關(guān)系
     *
     * @param pluginActivity 插件Activity
     * @return 殼子Activity
     */
    @Override
    public ComponentName onBindContainerActivity(ComponentName pluginActivity) {
        switch (pluginActivity.getClassName()) {
            /**
             * 這里配置對應(yīng)的對應(yīng)關(guān)系, 啟動不同啟動模式的Acitvity
             */
        }
        return new ComponentName(context, DEFAULT_ACTIVITY);
    }

    /**
     * 配置對應(yīng)宿主中預(yù)注冊的殼子contentProvider的信息
     */
    @Override
    public ContainerProviderInfo onBindContainerContentProvider(ComponentName pluginContentProvider) {
        return new ContainerProviderInfo(
                "com.tencent.shadow.runtime.container.PluginContainerContentProvider",
                "com.tencent.shadow.contentprovider.authority.dynamic");
    }

    @Override
    public List<BroadcastInfo> getBroadcastInfoList(String partKey) {
        List<ComponentManager.BroadcastInfo> broadcastInfos = new ArrayList<>();

        //如果有靜態(tài)廣播需要像下面代碼這樣注冊
//        if (partKey.equals(Constant.PART_KEY_PLUGIN_MAIN_APP)) {
//            broadcastInfos.add(
//                    new ComponentManager.BroadcastInfo(
//                            "com.tencent.shadow.demo.usecases.receiver.MyReceiver",
//                            new String[]{"com.tencent.test.action"}
//                    )
//            );
//        }
        return broadcastInfos;
    }

}

c 創(chuàng)建插件加載器

import android.content.Context;

import com.tencent.shadow.core.loader.ShadowPluginLoader;
import com.tencent.shadow.core.loader.managers.ComponentManager;
public class SamplePluginLoader extends ShadowPluginLoader {

    private final static String TAG = "shadow";

    private ComponentManager componentManager;

    public SamplePluginLoader(Context hostAppContext) {
        super(hostAppContext);
        componentManager = new SampleComponentManager(hostAppContext);
    }

    @Override
    public ComponentManager getComponentManager() {
        return componentManager;
    }
}

d 使用插件加載器

需要使用下面代碼中的路徑和類名:

package com.tencent.shadow.dynamic.loader.impl;

import android.content.Context;
import com.tencent.shadow.core.loader.ShadowPluginLoader;
import com.tencent.shadow.sample.loader.SamplePluginLoader;
import org.jetbrains.annotations.NotNull;

/**
 * 這個類的包名類名是固定的。
 * <p>
 * 見com.tencent.shadow.dynamic.loader.impl.DynamicPluginLoader#CORE_LOADER_FACTORY_IMPL_NAME
 */
public class CoreLoaderFactoryImpl implements CoreLoaderFactory {

    @NotNull
    @Override
    public ShadowPluginLoader build(@NotNull Context context) {
        return new SamplePluginLoader(context);
    }
}

注意如果要使用宿主的類霉涨,需要創(chuàng)建固定路徑下的 WhiteList 進(jìn)行注冊:

package com.tencent.shadow.dynamic.impl;

/**
 * 此類包名及類名固定
 * classLoader的白名單
 * PluginLoader可以加載宿主中位于白名單內(nèi)的類
 */
public interface WhiteList {
    String[] sWhiteList = new String[]
            {
                    "com.a.b",
            };
}

e 混淆

#kotlin一般性配置 START
-dontwarn kotlin.**
-keepclassmembers class **$WhenMappings {
    <fields>;
}
-keepclassmembers class kotlin.Metadata {
    public <methods>;
}
#kotlin一般性配置 END

#kotlin優(yōu)化性能 START
-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
    static void checkParameterIsNotNull(java.lang.Object, java.lang.String);
}
#kotlin優(yōu)化性能 END

-keep class org.slf4j.**{*;}
-dontwarn org.slf4j.impl.**

-keep class com.tencent.shadow.dynamic.host.**{*;}
-keep class com.tencent.shadow.dynamic.impl.**{*;}
-keep class com.tencent.shadow.dynamic.loader.**{*;}
-keep class com.tencent.shadow.core.common.**{*;}
-keep class com.tencent.shadow.core.loader.**{*;}
-keep class com.tencent.shadow.core.runtime.**{*;}

-dontwarn  com.tencent.shadow.dynamic.host.**
-dontwarn  com.tencent.shadow.dynamic.impl.**
-dontwarn  com.tencent.shadow.dynamic.loader.**
-dontwarn  com.tencent.shadow.core.common.**
-dontwarn  com.tencent.shadow.core.loader.**

4 在你的業(yè)務(wù)應(yīng)用工程gradle中配置插件

a 添加依賴

    //Shadow Transform后業(yè)務(wù)代碼會有一部分實(shí)際引用runtime中的類
    //如果不以compileOnly方式依賴,會導(dǎo)致其他Transform或者Proguard找不到這些類
    compileOnly "com.tencent.shadow.core:runtime:$shadow_version"

b 在gradle最底下配置插件

my-load 和 my-runtime 模塊生成的 apk 路徑及名字要對應(yīng)往枷,可以先build 生成一個 apk 查看路徑和名字, 插件apk路徑名字也一樣师溅,可以先build生成盾舌,再配置路徑妖谴。


apply plugin: 'com.tencent.shadow.plugin'

shadow {
    packagePlugin {
        pluginTypes {
            debug {
                loaderApkConfig = new Tuple2('my-loader-debug.apk', ':my-loader:assembleDebug')
                runtimeApkConfig = new Tuple2('my-runtime-debug.apk', ':my-runtime:assembleDebug')
                pluginApks {
                    pluginApk1 {
                        businessName = 'my-plugin'//businessName相同的插件,context獲取的Dir是相同的窑多。businessName留空技潘,表示和宿主相同業(yè)務(wù),直接使用宿主的Dir铲掐。
                        partKey = 'my-plugin'
                        buildTask = 'assembleDebug'
                        apkName = 'app-debug.apk'
                        apkPath = 'app/build/outputs/apk/debug/app-debug.apk'
                         // hostWhiteList = ["com.tencent.shadow.sample.host.lib"] // 配置允許插件訪問宿主的類
                    }
                }
            }

            release {
                loaderApkConfig = new Tuple2('my-loader-release-unsigned.apk', ':my-loader:assembleRelease')
                runtimeApkConfig = new Tuple2('my-runtime-release-unsigned.apk', ':my-runtime:assembleRelease')
                pluginApks {
                    pluginApk1 {
                        businessName = 'demo'
                        partKey = 'my-plugin'
                        buildTask = 'assembleRelease'
                        apkName = 'app-release-unsigned.apk'
                        apkPath = 'app/build/outputs/apk/release/app-release-unsigned.apk'
                         // hostWhiteList = ["com.tencent.shadow.sample.host.lib"] // 配置允許插件訪問宿主的類
                    }
                }
            }
        }

        loaderApkProjectPath = 'my-loader'

        runtimeApkProjectPath = 'my-runtime'

        version = 4
        compactVersion = [1, 2, 3]
        uuidNickName = "1.1.5"
    }
}

5 編譯

注意要keep住你從宿主打開插件的 Activity
使用命令,或者在Gradle 工具窗口點(diǎn)擊 packageDebugPlugin:

./gradlew packageDebugPlugin

生成zip路徑:
build/plugin-debug.zip

至此奔坟,插件工程完成蛀蜜。

將 manager.apk 和 plugin-debug.zip 放到指定位置即可享受滴某。

七霎奢、使用幫助

1 檢測當(dāng)前是否處于插件狀態(tài)下

public class PluginChecker {

    private static Boolean sPluginMode;

    /**
     * 檢測當(dāng)前是否處于插件狀態(tài)下
     * 這里先簡單通過訪問一個插件框架中的類是否成功來判斷
     * @return true 是插件模式
     */
    public static boolean isPluginMode() {
        if (sPluginMode == null) {
            try {
                PluginChecker.class.getClassLoader().loadClass("com.tencent.shadow.core.runtime.ShadowApplication");
                sPluginMode = true;
            } catch (ClassNotFoundException e) {
                sPluginMode = false;
            }
        }
        return sPluginMode;
    }

}

2 插件調(diào)用宿主類

宿主在打包時keep住插件要使用到的類名和方法帝美。

a 生成宿主 jar 包

在你的宿主依賴庫模塊 gradle 中配置命令:

//下面的jarPackage和afterEvaluate負(fù)責(zé)讓這個aar再生成一個輸出jar包的任務(wù)
def jarPackage(buildType) {
    return tasks.create("jar${buildType.capitalize()}Package", Copy) {
        def aarFile = file(project.buildDir.path + "/outputs/aar/${project.name}-${buildType}.aar")
        def outputDir = file(project.buildDir.path + "/outputs/jar")

        from zipTree(aarFile)
        into outputDir
        include 'classes.jar'
        rename 'classes.jar', "${project.name}-${buildType}.jar"
        group = 'build'
        description = '生成jar包'
    }.dependsOn(project.getTasksByName("assemble${buildType.capitalize()}", false).first())
}

afterEvaluate {
    android {
        buildTypes.findAll().each { buildType ->
            def buildTypeName = buildType.getName()
            jarPackage(buildTypeName)
        }
    }
}

會生成一個 jar包悼潭。

b 在插件中引用 jar

在應(yīng)用級 gradle 中添加依賴:

  //注意sample-host-lib要用compileOnly編譯而不打包在插件中舰褪。在packagePlugin任務(wù)中配置hostWhiteList允許插件訪問宿主的類占拍。
    compileOnly files("jar 包路徑")

c 在插件中使用宿主的類

跟引入了依賴庫一樣晃酒,可以直接使用贝次,這個類一定要在插件配置中配置好路徑并且在my-loader 模塊中 WhiteList 中注冊蛔翅,并且keep主類名和方法名搁宾。

3 將本地倉庫發(fā)布放到 gitee 或 github

示例:https://gitee.com/afra55/my-shadow
在 github 或 gitee 上創(chuàng)建一個空項(xiàng)目盖腿,找到本地倉庫直接推送到 github 或 gitee翩腐,比如shadow 直接將 com 文件夾及內(nèi)部相關(guān)文件提交即可:

image.png

使用

在應(yīng)用級 build.gralde 配置:

    allprojects {
        repositories {
            maven { url "https://gitee.com/afra55/my-shadow/raw/master" }
        }
    }

接下來就可以像在本地倉庫一樣使用依賴庫了何什。

持續(xù)更新

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末处渣,一起剝皮案震驚了整個濱河市罐栈,隨后出現(xiàn)的幾起案子荠诬,更是在濱河造成了極大的恐慌柑贞,老刑警劉巖钧嘶,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件康辑,死亡現(xiàn)場離奇詭異,居然都是意外死亡胸墙,警方通過查閱死者的電腦和手機(jī)迟隅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掠抬,“玉大人校哎,你說我怎么就攤上這事闷哆。” “怎么了劣坊?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵局冰,是天一觀的道長锐想。 經(jīng)常有香客問我赠摇,道長藕帜,這世上最難降的妖魔是什么洽故? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任时甚,我火速辦了婚禮荒适,結(jié)果婚禮上刀诬,老公的妹妹穿的比我還像新娘邪财。我一直安慰自己,他們只是感情好嘶伟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布奋早。 她就那樣靜靜地躺著耽装,像睡著了一般掉奄。 火紅的嫁衣襯著肌膚如雪姓建。 梳的紋絲不亂的頭發(fā)上缤苫,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天涣狗,我揣著相機(jī)與錄音舒憾,去河邊找鬼镀迂。 笑死,一個胖子當(dāng)著我的面吹牛窟赏,可吹牛的內(nèi)容都是我干的涯穷。 我是一名探鬼主播规哪,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诉稍,長吁一口氣:“原來是場噩夢啊……” “哼蚤告!你這毒婦竟也來了服爷?” 一聲冷哼從身側(cè)響起仍源,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤笼踩,失蹤者是張志新(化名)和其女友劉穎掘而,沒想到半個月后袍睡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體肋僧,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伪窖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了泥栖。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吧享。...
    茶點(diǎn)故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡钞它,死狀恐怖遭垛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情泵督,我是刑警寧澤小腊,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布秩冈,位于F島的核電站漩仙,受9級特大地震影響犹赖,放射性物質(zhì)發(fā)生泄漏麸折。R本人自食惡果不足惜粘昨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一芭析、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧吞瞪,春花似錦馁启、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至妖啥,卻和暖如春霉颠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背荆虱。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留奶镶,地道東北人惜姐。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓寝优,卻偏偏與公主長得像钻心,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評論 2 355