当前位置:网站首页>Agp7.0|kts makes a reinforced plug-in
Agp7.0|kts makes a reinforced plug-in
2022-06-30 09:03:00 【Silent Pinocchio】
Every time, use tools manually to reinforce , Very trouble , So I made a reinforced plug-in to improve productivity
The development environment uses AGP7.0.2 , Compare the previous version , The changes are quite big , I also stepped on many pits .
more AGP7.0 You can pay attention to brother shrimp's article
Nuggets :https://juejin.cn/post/7056395437544046606
We will complete it in the following steps :
- obtain apk product
- Get a signature
- Obtain reinforcement tools
- Reinforce
obtain APK
AGP7 obtain apk The way is different from before , We need the help of Variant API apk To get
Variant API yes Android Gradle Extension mechanism in plug-ins , You can manipulate various options , These options are usually used to affect Android build Of build In the configuration file DSL Set it up . You can also use Variant API visit build Intermediate and final artifacts created during , For example, class file 、 Consolidated list or APK/AAB file .
Here are some official examples
https://github.com/android/gradle-recipes/blob/agp-7.0/Kotlin/getApksTest/app/build.gradle.kts
AGP Introduced AndroidComponentsExtension , It can be for finalizeDsl()、beforeVariants() and onVariants() Register callback
- finalizeDsl: You can use this callback in DSL Object due to component ( variant ) Change it before it is locked .
VariantBuilderThe object is based on DSL Created from data contained in the .- beforeVariants This callback can be done through VariantBuilder It affects which components the system will create and some properties of the created components . It also supports build Process and generated artifacts .
- onVariants: In this callback , You can access the created
Variantobject , You can also include for themPropertyValue sets the value or provider , To calculate the delay .
In our customized plug-ins Get AndroidComponentsExtension, adopt AndroidComponentsExtension Of onVariant Callback registration Task
val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)
androidComponents.onVariants {
project.tasks.register<ApkTask>("${
it.name}DisplayApks") {
apkFolder.set(it.artifacts.get(SingleArtifact.APK))
builtArtifactsLoader.set(it.artifacts.getBuiltArtifactsLoader())
}
}
Next, let's look at our customized Task , These codes There are instances in the official code
abstract class ApkTask : DefaultTask() {
@get:InputFiles
abstract val apkFolder: DirectoryProperty
@get:Internal
abstract val builtArtifactsLoader: Property<BuiltArtifactsLoader>
@TaskAction
fun taskAction() {
val builtArtifacts = builtArtifactsLoader.get().load(apkFolder.get())
?: throw RuntimeException("Cannot load APKs")
builtArtifacts.elements.forEach {
val apk = File(it.outputFile)
}
}
}
task Of class If abstract Type of , Otherwise, the compiler will prompt final Type of mistake .
Get a signature
Get signature aspect , I didn't find any information in the official examples , I found a trace in the source code .
Look at us first app Next build.gradle.kts Configuration of signatures in
android {
signingConfigs {
create("release") {
storeFile = file("enjoy.keystore")
storePassword = "123456"
keyAlias = "enjoy"
keyPassword = "123456"
}
}
}
signingConfigs Is an interface type , Let's look at the implementation class :

With multiple implementation classes, we don't know which one to look for , Then look up one floor , Below android Method Source code
fun org.gradle.api.Project.`android`(configure: Action<com.android.build.gradle.internal.dsl.BaseAppModuleExtension>): Unit =
(this as org.gradle.api.plugins.ExtensionAware).extensions.configure("android", configure)
You can see that it uses BaseAppModuleExtension, Then we get BaseAppModuleExtension Can I get my signature , After I tried it, I was able to .
val baseAppModuleExtension = project.extensions.getByType(BaseAppModuleExtension::class.java)
val signingConfig = baseAppModuleExtension.signingConfigs.getByName("release")
So I got my signature
Obtain reinforcement tools
Reinforcement tool , We hope to be able to app Of gradle Can be dynamically configured in , Here is also a reference to the official plan :
https://github.com/gradle/kotlin-dsl-samples/blob/3c977388f7/samples/project-with-buildSrc/build.gradle.kts
Create an entity class first , The same is to abstract classes , What is needed is the tool address , User name and password
abstract class JiaguExtension {
abstract val jarPath: Property<String>
abstract val username: Property<String>
abstract val pwd: Property<String>
}
Then get it in the plug-in
val jiaguExtension = project.extensions.create<JiaguExtension>("jiagu")
Then we need to send the configuration information to task To carry out the reinforcement task .
Reinforce
The last step , We started to reinforce , Here we first introduce the use of reinforcement tools :
-login <username> You must log in for the first time <360 user name > <password> < The login password > -importsign <keystore_path> Import signature information < Key path > <keystore_password> < Key password > <alias> < Alias > <alias_password> < Alias password > -importmulpkg <mulpkg_filepath> Import multi-channel configuration information ,txt Format -showsign View the configured signature information -showmulpkg View the configured multi-channel information -deletemulpkg Clear the configured multi-channel information -help Display help information -config Configure reinforcement options ---------------------- Optional enhancement Services ------------------------------- [-crashlog] 【 Crash log analysis 】 [-x86] 【x86 Support 】 [-analyse] 【 Reinforcement data analysis 】 [-nocert] 【 Skip signature verification 】 [-piracy] 【 Piracy monitoring 】 ---------------------- Advanced reinforcement options ------------------------------- [-vmp] 【 whole VMP Protect 】 [-data] 【 Local data file protection 】 [-assets] 【 Resource file protection 】 [-filecheck] 【 Document integrity verification 】 [-ptrace] 【Ptrace Anti Injection 】 [-so] 【SO File protection 】 [-dex2c] 【dex2C Protect 】 [-string_obfus] 【 String encryption 】 [-dex_shadow] 【DexShadow】 [-so_private] 【SO Anti theft 】 [-double_check] 【 Double opening detection 】 ----------------------------------------------------------------- -config_so The configuration needs to be reinforced SO file , Space off -config_assets Configure resource files that need to be ignored , Space off -config_so_private Configure anti-theft SO file , Space off -showconfig Displays the configured reinforcement items -version Displays the current version number -update Upgrade to the latest version -jiagu <inputAPKpath> Reinforcement order <APK route > <outputPath> < The output path > [-autosign] 【 Automatic signature 】 [-automulpkg] 【 Automatic multi-channel 】 [-pkgparam mulpkg_filepath] 【 Custom file generation multi-channel 】
And then we passed project Provided commandLine Method to execute the reinforcement command
project.exec {
Sign in
commandLine("java", "-jar", jiagu.jarPath.get(), "-login", jiagu.username.get(), jiagu.pwd.get())
Configure signature
commandLine("java", "-jar", jiagu.jarPath.get(), "-importsign", signingConfig.storeFile?.absolutePath,
signingConfig.storePassword, signingConfig.keyAlias, signingConfig.keyPassword)
Reinforce
commandLine("java", "-jar", jiagu.jarPath.get(), "-jiagu", apk.absolutePath, apk.parent, "-autosign")
}
So far, the reinforcement function of the plug-in has been completed .
Use
And finally we use maven-publish The plug-in is pushed to the local for import and use
We first need to add the plug-in moudle Of gradle Plug in configuration in
gradlePlugin{
plugins {
register("jiaguPlugin") {
id = "jiagu-plugin"
implementationClass = "jiagu.JiaguPlugin"
}
}
}
This id It's what we used when we introduced it id,implementationClass It points to our customized Plugin
Finally, we publish to our local warehouse
group = "jiagu"
version = "1.0"
publishing {
repositories {
maven(url = "../repository")
}
}
Then the normal use of the import plug-in :
Project Of build.gradle.kts in :
repositories {
maven {
url = uri("./repository/") }
}
classpath("jiagu:jiagu-plugin:1.0")
app Of build.gradle.kts in :
plugins {
id("com.android.application")
id("kotlin-android")
id("jiagu-plugin")
}
jiagu{
jarPath.set("/Users/wyl/Downloads/360jiagubao_mac/jiagu/jiagu.jar")
username.set("182XXXX0810")
pwd.set("xiao")
}
Finally, you can see in Gradle See that the reinforcement plug-in already exists
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8kgHWpo6-1644843513344)(/Users/wyl/Library/Application Support/typora-user-images/image-20220207104006146.png)]](/img/d2/3ffc243f4ff6fd47ce6fbfc8db00b1.jpg)
Finally, let's see the effect :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-wjzcWbKE-1644843513345)(/Users/wyl/Library/Application Support/typora-user-images/image-20220207104235260.png)]](/img/a7/60730123838e4e11194a89a0e928fa.jpg)
other
besides , If you want to assembleDebug perhaps assembleDebug Insert reinforcement in task, You can use this solution
val apkProducer = project.tasks.register("apk${
it.name}Task", ApkTask2::class.java)
it.artifacts.use(apkProducer).wiredWithDirectories(
ApkTask2::inputApk,
ApkTask2::outputApk
).toTransform(SingleArtifact.APK)
abstract class ApkTask2 : DefaultTask() {
@get:InputDirectory
abstract val inputApk: DirectoryProperty
@get:OutputDirectories
abstract val outputApk: DirectoryProperty
@TaskAction
fun taskAction() {
val apks = File(inputApk.get().toString())
apks.listFiles()?.forEach {
if (it.name.endsWith(".apk")) {
val outPutFile = File(outputApk.get().toString() + "/out.apk")
// Perform reinforcement tasks
}
}
}
}
This is done every time assembleDebug perhaps assembleDebug The task will be carried out apk The reinforcement of .
ending
It's the end of it .
Address :https://github.com/WngYilei/Jiagu
Welcome to share , Put forward valuable opinions .
Reference resources :
Brother shrimp :https://juejin.cn/post/7056395437544046606
Official documents :https://github.com/gradle/kotlin-dsl-samples
Official documents :https://github.com/android/gradle-recipes
Official documents :https://developer.android.google.cn/studio/build/extend-agp?hl=zh_cn
边栏推荐
- Interpretation of orientedrcnn papers
- File upload component on success event, add custom parameters
- Detailed explanation of rect class
- Enhance the add / delete operation of for loop & iterator delete collection elements
- About Lombok's @data annotation
- A troubleshooting of CPU bottom falling
- [data analysis and display]
- Esp32 things (3): overview of the overall system design
- Redis design and Implementation (IV) | master-slave replication
- [kotlin collaboration process] complete the advanced kotlin collaboration process
猜你喜欢

vim 从嫌弃到依赖(21)——跨文件搜索

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which

Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"

基于Svelte3.x桌面端UI组件库Svelte UI
![[untitled]](/img/45/368c41a74bf0738369c58c5963fca0.jpg)
[untitled]

Based on svelte3 X desktop UI component library svelte UI

维基媒体基金会公布新商业产品“维基媒体企业”首批客户

Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)

Explanation on the use of password profiteering cracking tool Hydra

Flink Exception -- No ExecutorFactory found to execute the application
随机推荐
[JPEG] how to compile JPEG turbo library files on different platforms
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Interpretation of orientedrcnn papers
Detailed explanation of rect class
Bind threads to run on a specific CPU logical kernel
Torchvision loads the weight of RESNET except the full connection layer
File upload component on success event, add custom parameters
基于Svelte3.x桌面端UI组件库Svelte UI
Summary of common pytoch APIs
Unity basic lighting model
Rew acoustic test (II): offline test
CUDA realizes L2 European distance
Vite project require syntax compatibility problem solving require is not defined
挖财开户安全吗?怎么有人说不靠谱。
Invalid update: invalid number of sections. The number of sections contained in the table view after
Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
c#获取当前的时间戳
Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)
Flink SQL 自定义 Connector
Talk about the job experience of kotlin cooperation process