参考:Android Tencent Shadow插件接入指南
附上我的Git学习:https://github.com/sindicly/TencentShadowStudySindi.git
在使用本地仓库接入的时候遇到了很多问题,果断使用直接导入Shadow SDK
下面的步骤 至始至终都在一个Tencent-Shadow-Study工程项目中操作
拷贝SDK文件到工程
在settings.gradle添加:
includeBuild 'sdk/coding'
includeBuild 'sdk/core'
includeBuild 'sdk/dynamic'
在buildScripts/gradle下,创建文件maven.gradle:
task buildSdk() {
dependsOn gradle.includedBuild('core').task(':gradle-plugin:assemble')
dependsOn gradle.includedBuild('core').task(':common:jarReleasePackage')
dependsOn gradle.includedBuild('core').task(':loader:assembleRelease')
dependsOn gradle.includedBuild('core').task(':manager:assembleRelease')
dependsOn gradle.includedBuild('core').task(':runtime:jarReleasePackage')
dependsOn gradle.includedBuild('core').task(':activity-container:jarReleasePackage')
dependsOn gradle.includedBuild('core').task(':transform-kit:assemble')
dependsOn gradle.includedBuild('core').task(':transform-kit:testJar')
dependsOn gradle.includedBuild('core').task(':transform:assemble')
dependsOn gradle.includedBuild('core').task(':load-parameters:assembleRelease')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-host:jarReleasePackage')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-loader:jarReleasePackage')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-loader-impl:assembleRelease')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-manager:assembleRelease')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-host-multi-loader-ext:jarReleasePackage')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-manager-multi-loader-ext:assembleRelease')
}
task lintSdk() {
dependsOn gradle.includedBuild('core').task(':common:lint')
dependsOn gradle.includedBuild('core').task(':loader:lint')
dependsOn gradle.includedBuild('core').task(':manager:lint')
dependsOn gradle.includedBuild('core').task(':runtime:lint')
dependsOn gradle.includedBuild('core').task(':activity-container:lint')
dependsOn gradle.includedBuild('core').task(':load-parameters:lint')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-host:lint')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-loader-impl:lint')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-manager:lint')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-host-multi-loader-ext:lint')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-manager-multi-loader-ext:lint')
}
task jvmTestSdk() {
dependsOn gradle.includedBuild('core').task(':transform-kit:test')
dependsOn gradle.includedBuild('core').task(':transform:test')
dependsOn gradle.includedBuild('core').task(':gradle-plugin:test')
dependsOn ':test_third-party-transform_androidx:assembleDebug'
}
task androidTestSdk() {
dependsOn gradle.includedBuild('core').task(':manager:connectedDebugAndroidTest')
dependsOn ':test-dynamic-host:connectedDebugAndroidTest'
}
task testSdk() {
dependsOn jvmTestSdk
dependsOn androidTestSdk
}
apply plugin: 'maven-publish'
static def getDependencyNode(scope, groupId, artifactId, version) {
Node node = new Node(null, 'dependency')
node.appendNode('groupId', groupId)
node.appendNode('artifactId', artifactId)
node.appendNode('version', version)
node.appendNode('scope', scope)
return node
}
def gitShortRev() {
def gitCommit = ""
def proc = "git rev-parse --short HEAD".execute()
proc.in.eachLine { line -> gitCommit = line }
proc.err.eachLine { line -> println line }
proc.waitFor()
return gitCommit
}
def setScm(scm) {
scm.appendNode('connection', "https://github.com/${System.getenv("GITHUB_ACTOR")}/Shadow.git")
def commit
if ("${System.env.CI}".equalsIgnoreCase("true")) {
commit = System.getenv("GITHUB_SHA")
} else {
commit = gitShortRev()
}
scm.appendNode('url', "https://github.com/${System.getenv("GITHUB_ACTOR")}/Shadow/commit/$commit")
}
def setGeneratePomFileAndDepends(publicationName) {
model {
tasks."generatePomFileFor${publicationName.capitalize()}Publication" {
destination = file("$buildDir/pom/$publicationName-pom.xml")
dependsOn(buildSdk)
dependsOn(lintSdk)
}
}
}
def sourceJar(String name, String path) {
return tasks.create("source${name.capitalize()}Jar", Jar) {
group = "publishing"
description = "package ${name} source to jar"
from "$path/src/main/java"
from "$path/src/main/kotlin"
destinationDir = file("$path/build/libs/")
classifier = 'sources'
}
}
def publicationVersion = ext.ARTIFACT_VERSION
def coreGroupId = 'com.tencent.shadow.core'
def corePath = 'sdk/core'
def dynamicGroupId = 'com.tencent.shadow.dynamic'
def dynamicPath = 'sdk/dynamic'
publishing {
publications {
gradlePlugin(MavenPublication) {
groupId coreGroupId
artifactId 'gradle-plugin'
version publicationVersion
artifact("$corePath/gradle-plugin/build/libs/gradle-plugin.jar")
artifact sourceJar("gradlePlugin", "$corePath/gradle-plugin")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', 'org.jetbrains.kotlin', 'kotlin-stdlib-jdk7', kotlin_version))
dependencies.append(getDependencyNode('compile', 'com.android.tools.build', 'gradle', build_gradle_version))
dependencies.append(getDependencyNode('compile', coreGroupId, 'transform-kit', publicationVersion))
dependencies.append(getDependencyNode('compile', coreGroupId, 'transform', publicationVersion))
dependencies.append(getDependencyNode('compile', coreGroupId, 'runtime', publicationVersion))
dependencies.append(getDependencyNode('compile', coreGroupId, 'activity-container', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
common(MavenPublication) {
groupId coreGroupId
artifactId 'common'
version publicationVersion
artifact("$corePath/common/build/outputs/jar/common-release.jar")
artifact sourceJar("common", "$corePath/common")
pom.withXml {
def root = asNode()
def scm = root.appendNode('scm')
setScm(scm)
}
}
loadParameters(MavenPublication) {
groupId coreGroupId
artifactId 'load-parameters'
version publicationVersion
artifact("$corePath/load-parameters/build/outputs/aar/load-parameters-release.aar")
artifact sourceJar("loadParameters", "$corePath/load-parameters")
pom.withXml {
def root = asNode()
def scm = root.appendNode('scm')
setScm(scm)
}
}
coreLoader(MavenPublication) {
groupId coreGroupId
artifactId 'loader'
version publicationVersion
artifact("$corePath/loader/build/outputs/aar/loader-release.aar")
artifact sourceJar("loader", "$corePath/loader")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', 'org.jetbrains.kotlin', 'kotlin-stdlib-jdk7', kotlin_version))
dependencies.append(getDependencyNode('compile', coreGroupId, 'runtime', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'activity-container', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('compile', coreGroupId, 'load-parameters', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
coreManager(MavenPublication) {
groupId coreGroupId
artifactId 'manager'
version publicationVersion
artifact("$corePath/manager/build/outputs/aar/manager-release.aar")
artifact sourceJar("manager", "$corePath/manager")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('provided', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('compile', coreGroupId, 'load-parameters', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
runtime(MavenPublication) {
groupId coreGroupId
artifactId 'runtime'
version publicationVersion
artifact("$corePath/runtime/build/outputs/jar/runtime-release.jar")
artifact sourceJar("runtime", "$corePath/runtime")
pom.withXml {
def root = asNode()
def scm = root.appendNode('scm')
setScm(scm)
}
}
activityContainer(MavenPublication) {
groupId coreGroupId
artifactId 'activity-container'
version publicationVersion
artifact("$corePath/activity-container/build/outputs/jar/activity-container-release.jar")
artifact sourceJar("activity-container", "$corePath/activity-container")
pom.withXml {
def root = asNode()
def scm = root.appendNode('scm')
setScm(scm)
}
}
transformKit(MavenPublication) {
groupId coreGroupId
artifactId 'transform-kit'
version publicationVersion
artifact("$corePath/transform-kit/build/libs/transform-kit.jar")
artifact sourceJar("transformKit", "$corePath/transform-kit")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', 'org.jetbrains.kotlin', 'kotlin-stdlib-jdk7', kotlin_version))
dependencies.append(getDependencyNode('compile', 'com.android.tools.build', 'gradle', build_gradle_version))
dependencies.append(getDependencyNode('compile', 'org.javassist', 'javassist', '3.22.0-GA'))
def scm = root.appendNode('scm')
setScm(scm)
}
}
transformKitTest(MavenPublication) {
groupId coreGroupId
artifactId 'transform-kit-test'
version publicationVersion
artifact("$corePath/transform-kit/build/libs/test-transform-kit.jar")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', 'junit', 'junit', '4.12'))
def scm = root.appendNode('scm')
setScm(scm)
}
}
transform(MavenPublication) {
groupId coreGroupId
artifactId 'transform'
version publicationVersion
artifact("$corePath/transform/build/libs/transform.jar")
artifact sourceJar("transform", "$corePath/transform")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', coreGroupId, 'transform-kit', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicHost(MavenPublication) {
groupId dynamicGroupId
artifactId 'host'
version publicationVersion
artifact("$dynamicPath/dynamic-host/build/outputs/jar/dynamic-host-release.jar")
artifact sourceJar("dynamicHost", "$dynamicPath/dynamic-host")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', coreGroupId, 'common', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicHostMultiLoaderExt(MavenPublication) {
groupId dynamicGroupId
artifactId 'host-multi-loader-ext'
version publicationVersion
artifact("$dynamicPath/dynamic-host-multi-loader-ext/build/outputs/jar/dynamic-host-multi-loader-ext-release.jar")
artifact sourceJar("dynamicHostMultiLoaderExt", "$dynamicPath/dynamic-host-multi-loader-ext")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('compile', dynamicGroupId, 'host', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicLoader(MavenPublication) {
groupId dynamicGroupId
artifactId 'loader'
version publicationVersion
artifact("$dynamicPath/dynamic-loader/build/outputs/jar/dynamic-loader-release.jar")
artifact sourceJar("dynamicLoader", "$dynamicPath/dynamic-loader")
pom.withXml {
def root = asNode()
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicLoaderImpl(MavenPublication) {
groupId dynamicGroupId
artifactId 'loader-impl'
version publicationVersion
artifact("$dynamicPath/dynamic-loader-impl/build/outputs/aar/dynamic-loader-impl-release.aar")
artifact sourceJar("dynamicLoaderImpl", "$dynamicPath/dynamic-loader-impl")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', 'org.jetbrains.kotlin', 'kotlin-stdlib-jdk7', kotlin_version))
dependencies.append(getDependencyNode('compile', coreGroupId, 'loader', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'activity-container', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('provided', dynamicGroupId, 'host', publicationVersion))
dependencies.append(getDependencyNode('compile', dynamicGroupId, 'loader', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicManager(MavenPublication) {
groupId dynamicGroupId
artifactId 'manager'
version publicationVersion
artifact("$dynamicPath/dynamic-manager/build/outputs/aar/dynamic-manager-release.aar")
artifact sourceJar("dynamicManager", "$dynamicPath/dynamic-manager")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', coreGroupId, 'manager', publicationVersion))
dependencies.append(getDependencyNode('compile', dynamicGroupId, 'loader', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('provided', dynamicGroupId, 'host', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
dynamicManagerMultiLoaderExt(MavenPublication) {
groupId dynamicGroupId
artifactId 'manager-multi-loader-ext'
version publicationVersion
artifact("$dynamicPath/dynamic-manager-multi-loader-ext/build/outputs/aar/dynamic-manager-multi-loader-ext-release.aar")
artifact sourceJar("dynamicManagerMultiLoaderExt", "$dynamicPath/dynamic-manager-multi-loader-ext")
pom.withXml {
def root = asNode()
def dependencies = root.appendNode('dependencies')
dependencies.append(getDependencyNode('compile', coreGroupId, 'manager', publicationVersion))
dependencies.append(getDependencyNode('compile', dynamicGroupId, 'loader', publicationVersion))
dependencies.append(getDependencyNode('compile', dynamicGroupId, 'manager', publicationVersion))
dependencies.append(getDependencyNode('provided', coreGroupId, 'common', publicationVersion))
dependencies.append(getDependencyNode('provided', dynamicGroupId, 'host-multi-loader-ext', publicationVersion))
def scm = root.appendNode('scm')
setScm(scm)
}
}
}
repositories {
def useLocalCredential = false
Properties properties = new Properties()
def propertiesFile = project.rootProject.file('local.properties')
if (propertiesFile.exists()) {
properties.load(propertiesFile.newDataInputStream())
if ("${properties.getProperty('gpr.local')}".equalsIgnoreCase('true')) {
def user = properties.getProperty('gpr.user')
def key = properties.getProperty('gpr.key')
maven {
name = "GitHubPackages"
credentials {
username = user
password = key
}
url "https://maven.pkg.github.com/${user}/shadow"
}
useLocalCredential = true
}
}
if (!useLocalCredential && "${System.env.CI}".equalsIgnoreCase("true")) {
maven {
name = "GitHubPackages"
credentials {
username = System.getenv("GITHUB_ACTOR")
password = System.getenv("GITHUB_TOKEN")
}
url "https://maven.pkg.github.com/" + "${System.env.GITHUB_REPOSITORY}".toLowerCase()
}
} else {
mavenLocal()
}
}
}
setGeneratePomFileAndDepends('gradlePlugin')
setGeneratePomFileAndDepends('common')
setGeneratePomFileAndDepends('loadParameters')
setGeneratePomFileAndDepends('coreLoader')
setGeneratePomFileAndDepends('coreManager')
setGeneratePomFileAndDepends('runtime')
setGeneratePomFileAndDepends('activityContainer')
setGeneratePomFileAndDepends('transformKit')
setGeneratePomFileAndDepends('transformKitTest')
setGeneratePomFileAndDepends('transform')
setGeneratePomFileAndDepends('dynamicHost')
setGeneratePomFileAndDepends('dynamicHostMultiLoaderExt')
setGeneratePomFileAndDepends('dynamicLoader')
setGeneratePomFileAndDepends('dynamicLoaderImpl')
setGeneratePomFileAndDepends('dynamicManager')
setGeneratePomFileAndDepends('dynamicManagerMultiLoaderExt')
buildscript {
ext {
kotlin_version = "1.4.20"
build_gradle_version = '4.0.2'
}
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$build_gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
//allprojects {//已经在buildScripts/gradle/common.gradle配置
// repositories {
// google()
// jcenter()
// }
//}
apply from: 'buildScripts/gradle/common.gradle'
apply from: "buildScripts/gradle/maven.gradle"
task clean(type: Delete) {//定义任务
delete rootProject.buildDir
dependsOn gradle.includedBuild('coding').task(':checks:clean')//添加依赖
dependsOn gradle.includedBuild('coding').task(':lint:clean')
dependsOn gradle.includedBuild('coding').task(':code-generator:clean')
dependsOn gradle.includedBuild('core').task(':gradle-plugin:clean')
dependsOn gradle.includedBuild('core').task(':common:clean')
dependsOn gradle.includedBuild('core').task(':loader:clean')
dependsOn gradle.includedBuild('core').task(':manager:clean')
dependsOn gradle.includedBuild('core').task(':runtime:clean')
dependsOn gradle.includedBuild('core').task(':activity-container:clean')
dependsOn gradle.includedBuild('core').task(':transform:clean')
dependsOn gradle.includedBuild('core').task(':transform-kit:clean')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-host:clean')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-loader:clean')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-loader-impl:clean')
dependsOn gradle.includedBuild('dynamic').task(':dynamic-manager:clean')
}
```java
def gitShortRev() {
def gitCommit = ""
def proc = "git rev-parse --short HEAD".execute()
proc.in.eachLine { line -> gitCommit = line }
proc.err.eachLine { line -> println line }
proc.waitFor()
return gitCommit
}
allprojects {
ext.COMPILE_SDK_VERSION = 30
ext.BUILD_TOOLS_VERSION = "28.0.3"
ext.MIN_SDK_VERSION = 21
ext.TARGET_SDK_VERSION = 28
ext.VERSION_CODE = 1
ext.VERSION_NAME = "1.0"
ext.APP_APPLICATION_ID = 'com.test.shadow'
if ("${System.env.PUBLISH_RELEASE}".equalsIgnoreCase("true")) {
ext.VERSION_SUFFIX = ""
} else if ("${System.env.ORANGE}".equalsIgnoreCase("true")) {
ext.VERSION_SUFFIX = "-${System.env.ORANGE_COMMIT_SHORT}-SNAPSHOT"
} else {
ext.VERSION_SUFFIX = "-${gitShortRev()}-SNAPSHOT"
}
ext.ARTIFACT_VERSION = ext.VERSION_NAME + ext.VERSION_SUFFIX
repositories {
google()
jcenter()
}
//环境检查
envCheck()
}
def envCheck(){
//优化错误提示,不然会出现代码中找不到android依赖的问题
def jarFile = file("${System.getenv().get('ANDROID_HOME')}/platforms/android-${project.COMPILE_SDK_VERSION}/android.jar")
if(!jarFile.exists()){
throw new RuntimeException("Missing SDK Platform Android,API ${project.COMPILE_SDK_VERSION}。请确保以下文件存在: ${jarFile.absolutePath}")
}
}
在app/build.gradle添加:
android {
defaultConfig {
applicationId project.APP_APPLICATION_ID
//或者这样写:applicationId 'com.test.shadow'
}
sourceSets {
debug {
assets.srcDir('build/generated/assets/plugin-manager/debug/')
assets.srcDir('build/generated/assets/plugin-zip/debug/')
}
release {
assets.srcDir('build/generated/assets/plugin-manager/release/')
assets.srcDir('build/generated/assets/plugin-zip/release/')
}
}
}
dependencies {
implementation project(path: ':constants')//共同使用的常量库
implementation 'com.tencent.shadow.core:common'//AndroidLogLoggerFactory
implementation 'commons-io:commons-io:2.5'//sample-host从assets中复制插件用的
implementation 'com.tencent.shadow.dynamic:dynamic-host'//腾讯插件框架shadow
}
这里要求背景透明即可, 可根据自己需求修改,建议仅竖屏:
在app/values/themes.xml:
<style name="transparent_theme" 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>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.shadow">
<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/Theme.TencentShadowStudy">
//android:multiprocess="true"//表示多进程(多插件的时候使用)
//android:process=":plugin"//表示单进程(当个插件使用)
//android:theme="@style/transparent_theme" //theme需要注册成透明
//
<service
android:name=".service.MainPluginProcessService"
android:process=":main_plugin" />
<activity
android:name="com.test.plugin_runtime.PluginDefaultProxyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
android:hardwareAccelerated="true"
android:launchMode="standard"
android:process=":main_plugin"//要和上面注册的MainPluginProcessService的process属性值一致
android:screenOrientation="portrait"
android:theme="@style/transparent_theme"//theme需要注册成透明
/>
<activity
android:name="com.test.plugin_runtime.PluginSingleInstance1ProxyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
android:hardwareAccelerated="true"
android:launchMode="singleInstance"
android:process=":main_plugin"
android:screenOrientation="portrait"
android:theme="@style/transparent_theme" />
<activity
android:name="com.test.plugin_runtime.PluginSingleTask1ProxyActivity"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|screenLayout|fontScale|uiMode|orientation|screenSize|smallestScreenSize|layoutDirection"
android:hardwareAccelerated="true"
android:launchMode="singleTask"
android:process=":main_plugin"
android:screenOrientation="portrait"
android:theme="@style/transparent_theme" />
<provider
android:name="com.tencent.shadow.core.runtime.container.PluginContainerContentProvider"
android:authorities="com.tencent.shadow.sindi.contentprovider"
android:grantUriPermissions="true" /> //
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
PluginManager 是用来装载插件,PluginManager 通过加载一个单独的apk来创建的。
下面会说怎么生成这个apk,先知道在宿主中怎么用。
用来更新PluginManager
放在app/com.test.shadow.manager
package com.test.shadow.manager;
import com.tencent.shadow.dynamic.host.PluginManagerUpdater;
import java.io.File;
import java.util.concurrent.Future;
//实际只是获取PluginManager的apk存放路径
//这个FixedPathPmUpdater没有任何升级能力。直接将指定路径作为其升级结果。
public class FixedPathPmUpdater implements PluginManagerUpdater {
final private File apk;
public FixedPathPmUpdater(File apk) {
this.apk = apk;
}
/**
* @return true
表示之前更新过程中意外中断了
*/
@Override
public boolean wasUpdating() {
return false;
}
/**
* 更新
* @return 当前最新的PluginManager,可能是之前已经返回过的文件,但它是最新的了。
*/
@Override
public Future<File> update() {
return null;
}
/**
* 获取本地最新可用的
* @return null
表示本地没有可用的
*/
@Override
public File getLatest() {
return apk;
}
/**
* 查询是否可用
* @param file PluginManagerUpdater返回的file
* @return true
表示可用,false
表示不可用
*/
@Override
public Future<Boolean> isAvailable(final File file) {
return null;
}
}
放在app/com.test.shadow.service
package com.test.shadow.service;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.util.Log;
import com.tencent.shadow.dynamic.host.PluginProcessService;
//一个PluginProcessService(简称PPS)代表一个插件进程。插件进程由PPS启动触发启动。
//新建PPS子类允许一个宿主中有多个互不影响的插件进程。
public class MainPluginProcessService extends PluginProcessService {
public MainPluginProcessService() {
LoadPluginCallback.setCallback(new LoadPluginCallback.Callback() {
@Override
public void beforeLoadPlugin(String partKey) {
Log.e("MainPPS", "beforeLoadPlugin====>" +
"\tpartKey = [" + partKey + "]");
}
@Override
public void afterLoadPlugin(String partKey, ApplicationInfo applicationInfo, ClassLoader pluginClassLoader, Resources pluginResources) {
Log.e("MainPPS", "afterLoadPlugin=====>" +
"\tpartKey = [" + partKey + "], " +
"applicationInfo.className = [" + applicationInfo.className + "], " +
"applicationInfo.metaData = [" + applicationInfo.metaData + "], " +
"pluginClassLoader = [" + pluginClassLoader + "]," +
"pluginResources = [" + pluginResources + "]");
}
});
}
}
LoadPluginCallback.java:
package com.test.shadow.service;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
public class LoadPluginCallback {
private static Callback sCallback;
public static void setCallback(Callback callback) {
sCallback = callback;
}
public static Callback getCallback() {
return sCallback;
}
public interface Callback {
void beforeLoadPlugin(String partKey);
void afterLoadPlugin(String partKey, ApplicationInfo applicationInfo, ClassLoader pluginClassLoader, Resources pluginResources);
}
}
检查下是否在清单文件注册Service:
<service
android:name="com.test.shadow.service.MainPluginProcessService"
android:process=":main_plugin" />
package com.test.shadow;
import com.tencent.shadow.core.common.ILoggerFactory;
public class AndroidLogLoggerFactory implements ILoggerFactory {}
示例: https://github.com/Tencent/Shadow/blob/master/projects/sample/source/sample-host/src/main/java/com/tencent/shadow/sample/host/AndroidLogLoggerFactory.java
按照官方示例会出现:
在app/com.test.shadow
package com.test.shadow;
import android.app.ActivityManager;
import android.app.Application ;
import android.content.Context;
import android.os.Build;
import android.webkit.WebView;
import com.tencent.shadow.core.common.LoggerFactory;
import com.tencent.shadow.dynamic.host.DynamicPluginManager;
import com.tencent.shadow.dynamic.host.DynamicRuntime;
import com.tencent.shadow.dynamic.host.PluginManager;
import com.test.shadow.manager.FixedPathPmUpdater;
import java.io.File;
import java.util.concurrent.Future;
import static android.os.Process.myPid;
public class MyApplication extends Application {
private static MyApplication sApp;
private static PluginManager sPluginManager;//这个PluginManager对象在Manager升级前后是不变的。它内部持有具体实现,升级时更换具体实现
@Override
public void onCreate() {
super.onCreate();
sApp = this;
detectNonSdkApiUsageOnAndroidP();
setWebViewDataDirectorySuffix();
LoggerFactory.setILoggerFactory(new AndroidLogLoggerFactory());
if (isProcess(this, ":main_plugin")) {//TODO
//在全动态架构中,Activity组件没有打包在宿主而是位于被动态加载的runtime,
//为了防止插件crash后,系统自动恢复crash前的Activity组件,此时由于没有加载runtime而发生classNotFound异常,导致二次crash
//因此这里恢复加载上一次的runtime
DynamicRuntime.recoveryRuntime(this);
}
PluginHelper.getInstance().init(this);
}
private static void setWebViewDataDirectorySuffix() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return;
}
WebView.setDataDirectorySuffix(Application.getProcessName());
}
private static void detectNonSdkApiUsageOnAndroidP() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return;
}
boolean isRunningEspressoTest;
try {
Class.forName("androidx.test.espresso.Espresso");
isRunningEspressoTest = true;
} catch (Exception ignored) {
isRunningEspressoTest = false;
}
if (isRunningEspressoTest) {
return;
}
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
builder.detectNonSdkApiUsage();
StrictMode.setVmPolicy(builder.build());
}
public static MyApplication getApp() {
return sApp;
}
public void loadPluginManager(File apk) {
if (sPluginManager == null) {
sPluginManager = Shadow.getPluginManager(apk);
}
}
public PluginManager getPluginManager() {
return sPluginManager;
}
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);
}
}
在app/com.test.shadow.manager
package com.test.shadow.manager;
import android.content.Context;
import android.os.Environment;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.test.shadow.BuildConfig.DEBUG;
public class PluginHelper {
public final static String sPluginManagerName = "plugin-manager.apk";//动态加载的插件管理apk
/**
* 动态加载的插件包,里面包含以下几个部分,插件apk,插件框架apk(loader apk和runtime apk), apk信息配置关系json文件
*/
public final static String sPluginZip = DEBUG ? "plugin-debug.zip" : "plugin-release.zip";
public File pluginManagerFile;
public File pluginZipFile;
public ExecutorService singlePool = Executors.newSingleThreadExecutor();
private Context mContext;
private static PluginHelper sInstance = new PluginHelper();
public static PluginHelper getInstance() {
return sInstance;
}
private PluginHelper() {
}
public void init(Context context) {
pluginManagerFile = new File(context.getFilesDir(), sPluginManagerName);
pluginZipFile = new File(context.getFilesDir(), sPluginZip);
mContext = context.getApplicationContext();
singlePool.execute(() -> preparePlugin());
}
private void preparePlugin() {
try {
InputStream is = mContext.getAssets().open(sPluginManagerName);
FileUtils.copyInputStreamToFile(is, pluginManagerFile);
InputStream zip = mContext.getAssets().open(sPluginZip);
FileUtils.copyInputStreamToFile(zip, pluginZipFile);
} catch (IOException e) {
throw new RuntimeException("从assets中复制apk出错", e);
}
}
}
public class Shadow {
public static PluginManager getPluginManager(File apk){
final FixedPathPmUpdater fixedPathPmUpdater = new FixedPathPmUpdater(apk);
File tempPm = fixedPathPmUpdater.getLatest();
if (tempPm != null) {
return new DynamicPluginManager(fixedPathPmUpdater);
}
return null;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start_plugin"
android:text="启动插件" />
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="20dp"
android:orientation="horizontal" />
LinearLayout>
在app/com.test.shadow
public class MainActivity extends AppCompatActivity {
private LinearLayout ll;
private Handler mHandler = new Handler();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = findViewById(R.id.ll);
}
public void start_plugin(View view) {
PluginHelper.getInstance().singlePool.execute(new Runnable() {
@Override
public void run() {
MyApplication.getApp().loadPluginManager(PluginHelper.getInstance().pluginManagerFile);
/**
* @param context context
* @param formId 标识本次请求的来源位置,用于区分入口
* @param bundle 参数列表, 建议在参数列表加入自己的验证
* @param callback 用于从PluginManager实现中返回View
*/
Bundle bundle = new Bundle();//插件 zip,这几个参数也都可以不传,直接在 PluginManager 中硬编码
bundle.putString(Constant.KEY_PLUGIN_ZIP_PATH, PluginHelper.getInstance().pluginZipFile.getAbsolutePath());
bundle.putString(Constant.KEY_PLUGIN_NAME, Constant.PLUGIN_APP_NAME);// partKey 每个插件都有自己的 partKey 用来区分多个插件,如何配置在下面讲到
bundle.putString(Constant.KEY_ACTIVITY_CLASSNAME, "com.test.plugin_app.SplashActivity");//要启动的插件的Activity页面
bundle.putBundle(Constant.KEY_EXTRAS, new Bundle()); // 要传入到插件里的参数
MyApplication.getApp().getPluginManager().enter(MainActivity.this, Constant.FROM_ID_START_ACTIVITY, bundle, new EnterCallback() {
@Override
public void onShowLoadingView(View view) {
Log.e("PluginLoad", "onShowLoadingView");
loading(view);
//这里进行加载视图
}
@Override
public void onCloseLoadingView() {
Log.e("PluginLoad", "onCloseLoadingView");
}
@Override
public void onEnterComplete() {
// 启动成功
Log.e("PluginLoad", "onEnterComplete");
}
});
}
});
}
private void loading(View view) {
mHandler.post(new Runnable() {
@Override
public void run() {
ll.removeAllViews();
ll.addView(view);
}
});
}
}
创建了constants library包
package com.test.constants;
final public class Constant {
public static final String KEY_PLUGIN_ZIP_PATH = "key_plugin_zip_path";
public static final String KEY_ACTIVITY_CLASSNAME = "key_activity_classname";
public static final String KEY_EXTRAS = "key_extras";
public static final String KEY_PLUGIN_NAME = "key_plugin_name";
public static final String PLUGIN_APP_NAME = "plugin-app";
public static final int FROM_ID_NOOP = 1000;
public static final long FROM_ID_START_ACTIVITY = 1002;//标识启动的是Activity
public static final int FROM_ID_CALL_SERVICE = 1001;//标识启动的是Service
}
#noinspection ShrinkerUnresolvedReference
-keep class com.tencent.shadow.core.common.**{*;}
-keep class com.tencent.shadow.core.runtime.**{*;}
-keep class com.tencent.shadow.dynamic.host.**{*;}
创建一个新 Module(plugin-manager)。(按照以下步骤生成)
生成和 app模块 并列的 plugin-manager 模块
dependencies {
implementation 'com.tencent.shadow.dynamic:dynamic-manager'
implementation 'com.tencent.shadow.core:manager'
implementation 'com.tencent.shadow.dynamic:dynamic-loader'
compileOnly 'com.tencent.shadow.core:common-debug'
compileOnly 'com.tencent.shadow.dynamic:dynamic-host-debug'
implementation project(path: ':constants')
}
package com.test.plugin_manager;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import com.tencent.shadow.core.common.Logger;
import com.tencent.shadow.core.common.LoggerFactory;
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.FailedException;
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;
public abstract class FastPluginManager extends PluginManagerThatUseDynamicLoader {
private static final Logger mLogger = LoggerFactory.getLogger(FastPluginManager.class);
private ExecutorService mFixedPool = Executors.newFixedThreadPool(4);
public FastPluginManager(Context context) {
super(context);
}
/*安装插件*/
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);
}
/*启动插件Activity*/
public void startPluginActivity(InstalledPlugin installedPlugin, String partKey, Intent pluginIntent) throws RemoteException, TimeoutException, FailedException {
Intent intent = convertActivityIntent(installedPlugin, partKey, pluginIntent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPluginLoader.startActivityInPluginProcess(intent);
}
/*切换成插件Intent*/
public Intent convertActivityIntent(InstalledPlugin installedPlugin, String partKey, Intent pluginIntent) throws RemoteException, TimeoutException, FailedException {
loadPlugin(installedPlugin.UUID, partKey);
Map map = mPluginLoader.getLoadedPlugin();
Boolean isCall = (Boolean) map.get(partKey);
if (isCall == null || !isCall) {
mPluginLoader.callApplicationOnCreate(partKey);
}
return mPluginLoader.convertActivityIntent(pluginIntent);
}
private void loadPluginLoaderAndRuntime(String uuid, String partKey) throws RemoteException, TimeoutException, FailedException {
if (mPpsController == null) {
bindPluginProcessService(getPluginProcessServiceName(partKey));
waitServiceConnected(10, TimeUnit.SECONDS);
}
loadRunTime(uuid);
loadPluginLoader(uuid);
}
private void loadPlugin(String uuid, String partKey) throws RemoteException, TimeoutException, FailedException {
loadPluginLoaderAndRuntime(uuid, partKey);
Map map = mPluginLoader.getLoadedPlugin();
if (!map.containsKey(partKey)) {
mPluginLoader.loadPlugin(partKey);
}
}
protected abstract String getPluginProcessServiceName(String partKey);
}
SamplePluginManager.class
package com.test.plugin_manager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import com.tencent.shadow.core.manager.installplugin.InstalledPlugin;
import com.tencent.shadow.dynamic.host.EnterCallback;
import com.test.common.Constant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SamplePluginManager extends FastPluginManager {
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private Context mCurrentContext;
public SamplePluginManager(Context context) {
super(context);
mCurrentContext = context;
}
/**
* @return PluginManager实现的别名,用于区分不同PluginManager实现的数据存储路径
*/
@Override
protected String getName() {
return "plugin-manager";
}
/**
* @return 宿主so的ABI。插件必须和宿主使用相同的ABI。
*/
@Override
public String getAbi() {
return "";
}
/**
* @return 宿主中注册的PluginProcessService实现的类名
*/
@Override
protected String getPluginProcessServiceName(String partKey) {//在这里支持多个插件
if ("plugin-app".equals(partKey)) {//plugin-app:插件标识名
return "com.test.shadow.service.MainPluginProcessService";
} else {
//如果有默认PPS,可用return代替throw
throw new IllegalArgumentException("unexpected plugin load request意外的插件加载请求: " + partKey);
}
}
@Override
public void enter(final Context context, long fromId, Bundle bundle, final EnterCallback callback) {
if (fromId == Constant.FROM_ID_NOOP) {
//....
} else if (fromId == Constant.FROM_ID_START_ACTIVITY) {
onStartActivity(context, bundle, callback);
} else if (fromId == Constant.FROM_ID_CALL_SERVICE) {
//启动Service
} else {
throw new IllegalArgumentException("不认识的fromId==" + fromId);
}
}
private void onStartActivity(final Context context, Bundle bundle, final EnterCallback callback) {
final String pluginZipPath = bundle.getString(Constant.KEY_PLUGIN_ZIP_PATH);
final String partKey = bundle.getString(Constant.KEY_PLUGIN_NAME);
final String className = bundle.getString(Constant.KEY_ACTIVITY_CLASSNAME);
if (className == null) {
throw new NullPointerException("className == null");
}
final Bundle extras = bundle.getBundle(Constant.KEY_EXTRAS);
if (callback != null) {
final View view = LayoutInflater.from(mCurrentContext).inflate(R.layout.view_plugin_manager_loading, null);
callback.onShowLoadingView(view);
}
executorService.execute(() -> {
try {
InstalledPlugin installedPlugin = installPlugin(pluginZipPath, null, true);
Intent pluginIntent = new Intent();
pluginIntent.setClassName(
context.getPackageName(),
className
);
if (extras != null) {
pluginIntent.replaceExtras(extras);
}
startPluginActivity(installedPlugin, partKey, pluginIntent);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (callback != null) {
callback.onCloseLoadingView();
}
});
}
}
view_plugin_manager_loading.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:background="#fcfcfc">
<ProgressBar
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="正在启动插件" />
</LinearLayout>
需要使用下面的路径和类名:
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.test.plugin_manager.SamplePluginManager;
//此类包名及类名固定
public final class ManagerFactoryImpl implements ManagerFactory {
@Override
public PluginManagerImpl buildManager(Context context) {
return new SamplePluginManager(context);
}
}
package com.tencent.shadow.dynamic.impl;
/**
* 此类包名及类名固定
* classLoader的白名单
* PluginManager可以加载宿主中位于白名单内的类
* 这个白名单类暂时没啥用,可以在插件打包的时候配置白名单
*/
public interface WhiteList {
String[] sWhiteList = new String[]
{
//"com.tencent.host.shadow",
//"com.tencent.shadow.test.lib.constant",
};
}
#noinspection ShrinkerUnresolvedReference
-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 {*;}
./gradlew assembleDebug
之后会有文件生成,apk路径:
E:\AndroidStudioProjects\Tencent-Shadow-Study\plugin-manager\build\outputs\apk\debug\plugin-manager-debug.apk
这样就可以生成插件管理工具了 。
“plugin-runtime”应用模块主要放在宿主中注册的壳子,这个模块的 applicationd 可以随意。
dependencies {
implementation 'com.tencent.shadow.core:activity-container'
}
壳子路径包名(com.test.shadow.runtime)要和宿主中注册的保持一致:
壳子放在:plugin-runtime/com.test.plugin_runtime;
package com.test.plugin_runtime;
import android.annotation.SuppressLint;
import com.tencent.shadow.core.runtime.container.PluginContainerActivity;
//无需注册在这个模块的Manifest中,要注册在宿主的Manifest中。
@SuppressLint("Registered")
public class PluginDefaultProxyActivity extends PluginContainerActivity {}
public class PluginSingleInstance1ProxyActivity extends PluginContainerActivity {}
public class PluginSingleTask1ProxyActivity extends PluginContainerActivity {}
检查下宿主app/AndroidManifest.xml,配置的activity壳子路径是否一致。
<activity
android:name="com.test.plugin_runtime.PluginDefaultProxyActivity" />
<activity
android:name="com.test.plugin_runtime.PluginSingleInstance1ProxyActivity"/>
<activity
android:name="com.test.plugin_runtime.PluginSingleTask1ProxyActivity"/>
自定义的部分要修改成自己的
#noinspection ShrinkerUnresolvedReference
-keep class org.slf4j.**{*;}
-dontwarn org.slf4j.impl.**
-keep class com.tencent.shadow.core.runtime.**{*;}
#自定义:需要keep在宿主AndroidManifest.xml注册的壳子activity
-keep class com.test.plugin_runtime.**{*;}
dependencies {
implementation project(path: ':constants')
implementation 'com.tencent.shadow.core:loader'
implementation 'com.tencent.shadow.dynamic:dynamic-loader'
implementation 'com.tencent.shadow.dynamic:dynamic-loader-impl'
compileOnly 'com.tencent.shadow.core:runtime-debug'
compileOnly 'com.tencent.shadow.core:activity-container-debug'
compileOnly 'com.tencent.shadow.core:common-debug'
compileOnly 'com.tencent.shadow.dynamic:dynamic-host-debug'//下面这行依赖是为了防止在proguard的时候找不到LoaderFactory接口
}
package com.test.plugin_loader;
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 org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class SampleComponentManager extends ComponentManager {
/**
* sample-runtime 模块中定义的壳子Activity,需要在宿主AndroidManifest.xml注册
*/
private static final String DEFAULT_ACTIVITY = "com.test.plugin_runtime.PluginDefaultProxyActivity";
private static final String SINGLE_INSTANCE_ACTIVITY = "com.test.plugin_runtime.PluginSingleInstance1ProxyActivity";
private static final String SINGLE_TASK_ACTIVITY = "com.test.plugin_runtime.PluginSingleTask1ProxyActivity";
private Context context;
public SampleComponentManager(Context context) {
this.context = context;
}
/**
* 配置插件Activity 到 壳子Activity的对应关系
*
* @param pluginActivity 插件Activity
* @return 壳子Activity
*/
@Override
public ComponentName onBindContainerActivity(ComponentName pluginActivity) {
switch (pluginActivity.getClassName()) {
//这里配置对应的对应关系
}
System.out.println("壳子:PluginDefaultProxyActivity");
return new ComponentName(context, DEFAULT_ACTIVITY);
}
/**
* 配置对应宿主中预注册的壳子contentProvider的信息
*/
@Override
public ContainerProviderInfo onBindContainerContentProvider(ComponentName pluginContentProvider) {
return new ContainerProviderInfo(
"com.tencent.shadow.runtime.container.PluginContainerContentProvider",
"com.tencent.shadow.sindi.contentprovider");
}
@Nullable
@Override
public List<BroadcastInfo> getBroadcastInfoList(@NotNull String s) {
List<ComponentManager.BroadcastInfo> broadcastInfos = new ArrayList<>();
//如果有静态广播需要像下面代码这样注册
// 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;
}
}
package com.test.plugin_loader;
import android.content.Context;
import com.tencent.shadow.core.loader.ShadowPluginLoader;
import com.tencent.shadow.core.loader.managers.ComponentManager;
import com.test.plugin_loader.SampleComponentManager;
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;
}
}
需要使用下面代码中的路径和类名:
package com.tencent.shadow.dynamic.loader.impl;
import android.content.Context;
import com.tencent.shadow.core.loader.ShadowPluginLoader;
import com.tencent.shadow.dynamic.loader.impl.CoreLoaderFactory;
import com.test.plugin_loader.SamplePluginLoader;
import org.jetbrains.annotations.NotNull;
//这个类的包名类名是固定的。
//见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);
}
}
注意如果要使用宿主的类,需要创建固定路径下的 WhiteList 进行注册:(WhiteList 路径是 com.tencent.shadow.dynamic.impl;)
package com.tencent.shadow.dynamic.impl;
/**
* 此类包名及类名固定
* classLoader的白名单
* PluginLoader可以加载宿主中位于白名单内的类
*/
public interface WhiteList {
String[] sWhiteList = new String[]{
//"com.a.b",
};
}
#noinspection ShrinkerUnresolvedReference
#kotlin一般性配置 START
-dontwarn kotlin.**
-keepclassmembers class **$WhenMappings {
<fields>;
}
-keepclassmembers class kotlin.Metadata {
public <methods>;
}
#kotlin一般性配置 END
#kotlin优化性能 START
-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
static void checkParameterIsNotNull(java.lang.Object, java.lang.String);
}
#kotlin优化性能 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.**
android {
defaultConfig {
applicationId project.APP_APPLICATION_ID
//或者这样写:applicationId 'com.test.shadow'
}
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hahahhahahahh 跑起来 冲啊"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.plugin_app">//这个不需要和宿主的applicationId(包名)一致
<application
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/Theme.TencentShadowStudy">
<activity android:name="com.test.plugin_app.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my-load 和 my-runtime 模块生成的 apk 路径及名字要对应,可以先build 生成一个 apk 查看路径和名字, 插件apk路径名字也一样,可以先build生成,再配置路径。
以下脚本:插件+ my-load + my-runtime自动生成zip脚本
buildscript {//这个模块要放在plugins {} 之前
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.tencent.shadow.core:runtime-debug'
classpath 'com.tencent.shadow.core:activity-container-debug'
classpath 'com.tencent.shadow.core:gradle-plugin'
classpath 'org.javassist:javassist:3.22.0-GA'
}
}
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
。。。
defaultConfig {
applicationId project.APP_APPLICATION_ID
}
}
。。。
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//Shadow Transform后业务代码会有一部分实际引用runtime中的类
//如果不以compileOnly方式依赖,会导致其他Transform或者Proguard找不到这些类
compileOnly 'com.tencent.shadow.core:runtime-debug'
}
apply plugin: 'com.tencent.shadow.plugin'
shadow {
transform {
// useHostContext = ['abc']
}
packagePlugin {
pluginTypes {
debug {
loaderApkConfig = new Tuple2('plugin-loader-debug.apk', ':plugin-loader:assembleDebug')
runtimeApkConfig = new Tuple2('plugin-runtime-debug.apk', ':plugin-runtime:assembleDebug')
pluginApks {
pluginApk1 {
businessName = 'plugin-app'
partKey = 'plugin-app'
buildTask = ':plugin-app:assembleDebug'
apkName = 'plugin-app-debug.apk'
apkPath = 'plugin-app/build/outputs/apk/debug/plugin-app-debug.apk'
}
}
}
release {
loaderApkConfig = new Tuple2('plugin-loader-release.apk', ':plugin-loader:assembleRelease')
runtimeApkConfig = new Tuple2('plugin-runtime-release.apk', ':plugin-runtime:assembleRelease')
pluginApks {
pluginApk1 {
businessName = 'plugin-app'
partKey = 'plugin-app'
buildTask = ':plugin-app:assembleRelease'
apkName = 'plugin-app-release.apk'
apkPath = 'plugin-app/build/outputs/apk/release/plugin-app-release.apk'
}
}
}
}
loaderApkProjectPath = 'plugin-loader'
runtimeApkProjectPath = 'plugin-runtime'
version = 1
compactVersion = [1, 2, 3]
uuidNickName = "1.0"
}
}
在app/build.gradle
def createCopyTask(projectName, buildType, name, apkName, inputFile, taskName) {
//E:\AndroidStudioProjects\TencentShadowStudy\app\build\generated\assets\...
def outputFile = file("${getBuildDir()}/generated/assets/${name}/${buildType}/${apkName}")
outputFile.getParentFile().mkdirs()
return tasks.create("copy${buildType.capitalize()}${name.capitalize()}Task", Copy) {
group = 'build'
description = "复制${name}到assets中."
from(inputFile.getParent()) {
include(inputFile.name)
rename { outputFile.name }
}
into(outputFile.getParent())
}.dependsOn("${projectName}:${taskName}")
}
def generateAssets(generateAssetsTask, buildType) {//以下是自动生成插件
def moduleName = 'plugin-manager'
//E:\AndroidStudioProjects\TencentShadowStudy\plugin-manager\build\outputs\apk\debug\plugin-manager-debug.apk
def pluginManagerApkFile = file("${project(":plugin-manager").getBuildDir()}" + "/outputs/apk/${buildType}/" + "${moduleName}-${buildType}.apk")
generateAssetsTask.dependsOn createCopyTask(
':plugin-manager',
buildType,
moduleName,
'plugin-manager.apk',
pluginManagerApkFile,
"assemble${buildType.capitalize()}"//打包apk的任务栈名(编译器自带) assemblePlugin
)
//E:\AndroidStudioProjects\TencentShadowStudy\build\plugin-debug.zip
def pluginZip = file("${getRootProject().getBuildDir()}/plugin-${buildType}.zip")
generateAssetsTask.dependsOn createCopyTask(
':plugin-app',//模块名 TODO
buildType,//编译版本类型:Debug或者Release
'plugin-zip',//TODO
"plugin-${buildType}.zip",//生成的zip名
pluginZip,//输入文件
"package${buildType.capitalize()}Plugin"//打包zip的任务栈名(编译器自带) packageDebugPlugin
)
}
//在task被添加的时候定义依赖关系
tasks.whenTaskAdded { task ->
if (task.name == "generateDebugAssets") {
generateAssets(task, 'debug')
}
if (task.name == "generateReleaseAssets") {
generateAssets(task, 'release')
}
}
然后,就这样结束了