├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── cn │ │ └── hx │ │ └── plugin │ │ └── junkcode │ │ └── demo │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── cn │ │ │ └── hx │ │ │ └── plugin │ │ │ └── junkcode │ │ │ └── demo │ │ │ ├── AppApplication.kt │ │ │ └── MainActivity.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── cn │ └── hx │ └── plugin │ └── junkcode │ └── demo │ └── ExampleUnitTest.kt ├── bintray-release.gradle ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── project.properties └── src │ └── main │ ├── groovy │ └── cn │ │ └── hx │ │ └── plugin │ │ └── junkcode │ │ ├── ext │ │ ├── AndroidJunkCodeExt.groovy │ │ └── JunkCodeConfig.groovy │ │ ├── plugin │ │ └── AndroidJunkCodePlugin.groovy │ │ ├── task │ │ └── AndroidJunkCodeTask.groovy │ │ └── template │ │ ├── ManifestTemplate.groovy │ │ └── ResTemplate.groovy │ └── resources │ └── META-INF │ └── gradle-plugins │ └── android-junk-code.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | /repo -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android垃圾代码生成插件 2 | 3 | [![Download](https://api.bintray.com/packages/qq549631030/maven/AndroidJunkCode/images/download.svg) ](https://bintray.com/qq549631030/maven/AndroidJunkCode/_latestVersion) 4 | 5 | 此插件用于做马甲包时,减小马甲包与主包的代码相似度,避免被OPPO、VIVO等应用市场识别为马甲包。 6 | 7 | ### 使用方法 8 | 9 | 根目录的build.gradle中: 10 | ``` 11 | buildscript { 12 | dependencies { 13 | classpath "cn.hx.plugin:android-junk-code:1.0.2" 14 | } 15 | } 16 | ``` 17 | app目录的build.gradle模块中: 18 | ``` 19 | apply plugin: 'com.android.application' 20 | apply plugin: 'android-junk-code' 21 | 22 | android { 23 | //xxx 24 | } 25 | 26 | android.applicationVariants.all { variant -> 27 | switch (variant.name) { 28 | case "debug": 29 | case "release": 30 | androidJunkCode.configMap.put(variant.name, { 31 | packageBase = "cn.hx.plugin.ui" //生成java类根包名 32 | packageCount = 30 //生成包数量 33 | activityCountPerPackage = 3 //每个包下生成Activity类数量 34 | otherCountPerPackage = 50 //每个包下生成其它类的数量 35 | methodCountPerClass = 20 //每个类下生成方法数量 36 | resPrefix = "junk_" //生成的layout、drawable、string等资源名前缀 37 | drawableCount = 300 //生成drawable资源数量 38 | stringCount = 300 //生成string数量 39 | }) 40 | break 41 | } 42 | } 43 | ``` 44 | 45 | ### 生成文件所有目录 46 | build/generated/source/junk 47 | 48 | ### 使用插件[methodCount](https://github.com/KeepSafe/dexcount-gradle-plugin)对比 49 | 50 | #### 未加垃圾代码 51 | ``` 52 | Total methods in app-debug.apk: 26162 (39.92% used) 53 | Total fields in app-debug.apk: 12771 (19.49% used) 54 | Total classes in app-debug.apk: 2897 (4.42% used) 55 | Methods remaining in app-debug.apk: 39373 56 | Fields remaining in app-debug.apk: 52764 57 | Classes remaining in app-debug.apk: 62638 58 | ``` 59 | 60 | #### 加了垃圾代码 61 | ``` 62 | Total methods in app-release-unsigned.apk: 59733 (91.15% used) 63 | Total fields in app-release-unsigned.apk: 13462 (20.54% used) 64 | Total classes in app-release-unsigned.apk: 4488 (6.85% used) 65 | Methods remaining in app-release-unsigned.apk: 5802 66 | Fields remaining in app-release-unsigned.apk: 52073 67 | Classes remaining in app-release-unsigned.apk: 61047 68 | ``` 69 | 增加了1591个类33571个方法 -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | apply plugin: 'android-junk-code' 5 | apply plugin: 'com.getkeepsafe.dexcount' 6 | 7 | android { 8 | compileSdkVersion 29 9 | 10 | defaultConfig { 11 | applicationId "cn.hx.plugin.junkcode.demo" 12 | minSdkVersion 16 13 | targetSdkVersion 29 14 | versionCode 1 15 | versionName "1.0" 16 | multiDexEnabled true 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | release { 22 | minifyEnabled false 23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | } 27 | 28 | android.applicationVariants.all { variant -> 29 | switch (variant.name) { 30 | case "release": 31 | androidJunkCode.configMap.put(variant.name, { 32 | packageBase = "cn.hx.plugin.ui" 33 | packageCount = 30 34 | activityCountPerPackage = 3 35 | otherCountPerPackage = 50 36 | methodCountPerClass = 20 37 | resPrefix = "junk_" 38 | drawableCount = 300 39 | stringCount = 300 40 | }) 41 | break 42 | } 43 | } 44 | 45 | dependencies { 46 | implementation fileTree(dir: "libs", include: ["*.jar"]) 47 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 48 | implementation 'androidx.multidex:multidex:2.0.1' 49 | implementation 'androidx.core:core-ktx:1.3.0' 50 | implementation 'androidx.appcompat:appcompat:1.1.0' 51 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 52 | testImplementation 'junit:junit:4.13' 53 | androidTestImplementation 'androidx.test.ext:junit:1.1.1' 54 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 55 | 56 | } 57 | 58 | 59 | // 60 | //afterEvaluate { 61 | // project.tasks.all { task -> 62 | // task.doLast { 63 | // task.inputs.files.each { fileTemp -> 64 | // println 'input file:' + fileTemp.absolutePath 65 | // } 66 | // 67 | // println '---------------------------------------------------' 68 | // task.outputs.files.each { fileTemp -> 69 | // println 'output file:' + fileTemp.absolutePath 70 | // } 71 | // } 72 | // } 73 | //} 74 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/cn/hx/plugin/junkcode/demo/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.demo 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("cn.hx.plugin.junkcode.demo", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/cn/hx/plugin/junkcode/demo/AppApplication.kt: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.demo 2 | 3 | import android.app.Application 4 | import android.content.Context 5 | import androidx.multidex.MultiDex 6 | 7 | class AppApplication : Application() { 8 | override fun attachBaseContext(base: Context?) { 9 | super.attachBaseContext(base) 10 | MultiDex.install(this) 11 | } 12 | } -------------------------------------------------------------------------------- /app/src/main/java/cn/hx/plugin/junkcode/demo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.demo 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | 6 | class MainActivity : AppCompatActivity() { 7 | override fun onCreate(savedInstanceState: Bundle?) { 8 | super.onCreate(savedInstanceState) 9 | setContentView(R.layout.activity_main) 10 | } 11 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidJunkCode 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/test/java/cn/hx/plugin/junkcode/demo/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.demo 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /bintray-release.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.novoda.bintray-release' 2 | apply plugin: 'maven' 3 | // This generates sources.jar 4 | task sourcesJar(type: Jar) { 5 | from sourceSets.main.java.srcDirs 6 | from sourceSets.main.groovy.srcDirs 7 | archiveClassifier.convention('sources') 8 | } 9 | 10 | // This generates javadoc.jar 11 | task javadocJar(type: Jar, dependsOn: javadoc) { 12 | from javadoc.destinationDir 13 | archiveClassifier.convention('javadoc') 14 | } 15 | 16 | artifacts { 17 | archives javadocJar 18 | archives sourcesJar 19 | } 20 | 21 | // javadoc configuration 22 | javadoc { 23 | options { 24 | encoding "UTF-8" 25 | charSet 'UTF-8' 26 | author true 27 | } 28 | } 29 | 30 | afterEvaluate { 31 | Task bintrayUploadTask = tasks.findByName('bintrayUpload') 32 | Task uploadArchivesTask = tasks.findByName('uploadArchives') 33 | if (bintrayUploadTask != null && uploadArchivesTask != null) { 34 | bintrayUploadTask.dependsOn uploadArchivesTask 35 | } 36 | tasks.withType(Javadoc) { 37 | options.addStringOption('Xdoclint:none', '-quiet') 38 | options.addStringOption('encoding', 'UTF-8') 39 | } 40 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | ext.kotlin_version = "1.3.72" 4 | repositories { 5 | google() 6 | jcenter() 7 | maven { 8 | url './repo' 9 | } 10 | } 11 | dependencies { 12 | classpath "com.android.tools.build:gradle:4.0.0" 13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 14 | classpath 'com.novoda:bintray-release:0.9.2' 15 | classpath "cn.hx.plugin:android-junk-code:1.0.2" 16 | classpath "com.getkeepsafe.dexcount:dexcount-gradle-plugin:1.0.3" 17 | 18 | // NOTE: Do not place your application dependencies here; they belong 19 | // in the individual module build.gradle files 20 | } 21 | } 22 | 23 | allprojects { 24 | repositories { 25 | google() 26 | jcenter() 27 | } 28 | } 29 | 30 | task clean(type: Delete) { 31 | delete rootProject.buildDir 32 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndroidLMY/AndroidJunkCode/68eca150c19cfe2545bc1dd83a30c644a8d84c65/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jun 01 09:21:30 CST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'maven' 3 | 4 | dependencies { 5 | implementation fileTree(dir: 'libs', include: ['*.jar']) 6 | implementation gradleApi() 7 | implementation localGroovy() 8 | implementation 'com.squareup:javapoet:1.11.1' 9 | implementation 'com.android.tools.build:gradle:3.0.0' 10 | } 11 | 12 | apply from: rootProject.projectDir.absolutePath + "/bintray-release.gradle" 13 | 14 | // load properties 15 | Properties properties = new Properties() 16 | File localPropertiesFile = project.file("$rootProject.projectDir.absolutePath/local.properties"); 17 | if (localPropertiesFile.exists()) { 18 | properties.load(localPropertiesFile.newDataInputStream()) 19 | } 20 | File projectPropertiesFile = project.file("project.properties"); 21 | if (projectPropertiesFile.exists()) { 22 | properties.load(projectPropertiesFile.newDataInputStream()) 23 | } 24 | 25 | def projectName = properties.getProperty("project.name") 26 | def projectGroupId = properties.getProperty("project.groupId") 27 | def projectArtifactId = properties.getProperty("project.artifactId") 28 | def projectArtifactVersion = properties.getProperty("project.artifactVersion") 29 | def projectSiteUrl = properties.getProperty("project.siteUrl") 30 | def projectGitUrl = properties.getProperty("project.gitUrl") 31 | def projectDesc = properties.getProperty("project.desc") 32 | 33 | def bintray_Org = properties.getProperty("bintray.org") 34 | def bintray_User = properties.getProperty("bintray.user") 35 | def bintrayApikey = properties.getProperty("bintray.apikey") 36 | def mavenUserName = properties.getProperty("mavenUserName") 37 | def mavenUserPassword = properties.getProperty("mavenUserPassword") 38 | 39 | publish { 40 | groupId = projectGroupId 41 | artifactId = projectArtifactId 42 | uploadName = projectName 43 | website = projectSiteUrl 44 | repository = projectGitUrl 45 | desc = projectDesc 46 | publishVersion = projectArtifactVersion 47 | userOrg = bintray_Org 48 | bintrayUser = bintray_User 49 | bintrayKey = bintrayApikey 50 | dryRun = false 51 | } 52 | 53 | uploadArchives { 54 | repositories { 55 | mavenDeployer { 56 | // repository(url: 'your repositories') { 57 | // authentication(userName: mavenUserName, password: mavenUserPassword) 58 | // } 59 | repository(url: uri("../repo")) 60 | pom.version = projectArtifactVersion 61 | pom.artifactId = 'android-junk-code' 62 | pom.groupId = 'cn.hx.plugin' 63 | pom.project { 64 | name = project.name 65 | packaging = 'jar' 66 | description = 'description' 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /library/project.properties: -------------------------------------------------------------------------------- 1 | #project 2 | project.name=AndroidJunkCode 3 | project.groupId=cn.hx.plugin 4 | project.artifactId=android-junk-code 5 | project.artifactVersion=1.0.2 6 | project.siteUrl=https://github.com/qq549631030/AndroidJunkCode 7 | project.gitUrl=https://github.com/qq549631030/AndroidJunkCode.git 8 | project.desc=generate junk code for android -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/ext/AndroidJunkCodeExt.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.ext 2 | 3 | class AndroidJunkCodeExt { 4 | Map> configMap = [:] 5 | } -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/ext/JunkCodeConfig.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.ext 2 | 3 | import org.gradle.api.tasks.Input 4 | 5 | class JunkCodeConfig { 6 | @Input 7 | String packageBase = "" 8 | @Input 9 | int packageCount = 0 10 | @Input 11 | int activityCountPerPackage = 0 12 | @Input 13 | int otherCountPerPackage = 0 14 | @Input 15 | int methodCountPerClass = 0 16 | @Input 17 | String resPrefix = "junk_" 18 | @Input 19 | int drawableCount = 0 20 | @Input 21 | int stringCount = 0 22 | } -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/plugin/AndroidJunkCodePlugin.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.plugin 2 | 3 | import cn.hx.plugin.junkcode.ext.AndroidJunkCodeExt 4 | import cn.hx.plugin.junkcode.ext.JunkCodeConfig 5 | import cn.hx.plugin.junkcode.task.AndroidJunkCodeTask 6 | import com.android.build.gradle.AppExtension 7 | import com.android.build.gradle.api.ApplicationVariant 8 | import org.gradle.api.Plugin 9 | import org.gradle.api.Project 10 | 11 | class AndroidJunkCodePlugin implements Plugin { 12 | 13 | @Override 14 | void apply(Project project) { 15 | def android = project.extensions.getByType(AppExtension) 16 | if (!android) { 17 | throw IllegalArgumentException("must apply this plugin after 'com.android.application'") 18 | } 19 | def generateJunkCodeExt = project.extensions.create("androidJunkCode", AndroidJunkCodeExt) 20 | project.afterEvaluate { 21 | android.applicationVariants.all { variant -> 22 | def variantName = variant.name 23 | Closure junkCodeConfig = generateJunkCodeExt.configMap[variantName] 24 | if (junkCodeConfig) { 25 | def dir = new File(project.buildDir, "generated/source/junk/$variantName") 26 | String packageName = findPackageName(variant) 27 | def generateJunkCodeTask = project.task("generate${variantName.capitalize()}JunkCode", type: AndroidJunkCodeTask) { 28 | junkCodeConfig.delegate = config 29 | junkCodeConfig.resolveStrategy = DELEGATE_FIRST 30 | junkCodeConfig.call() 31 | manifestPackageName = packageName 32 | outDir = dir 33 | } 34 | //将自动生成的AndroidManifest.xml加入到一个未被占用的manifest位置(如果都占用了就不合并了,通常较少出现全被占用情况) 35 | for (int i = variant.sourceSets.size() - 1; i >= 0; i--) { 36 | def sourceSet = variant.sourceSets[i] 37 | if (!sourceSet.manifestFile.exists()) { 38 | android.sourceSets."${sourceSet.name}".manifest.srcFile(new File(dir, "AndroidManifest.xml").absolutePath) 39 | break 40 | } 41 | } 42 | android.sourceSets."${variantName}".res.srcDir(new File(dir, "res")) 43 | variant.registerJavaGeneratingTask(generateJunkCodeTask, new File(dir, "java")) 44 | //在执行generateBuildConfig之前执行generateJunkCodeTask 45 | variant.generateBuildConfigProvider.get().dependsOn(generateJunkCodeTask) 46 | } 47 | } 48 | } 49 | } 50 | 51 | 52 | /** 53 | * 从AndroidManifest.xml找到package name 54 | * @param variant 55 | * @return 56 | */ 57 | static String findPackageName(ApplicationVariant variant) { 58 | String packageName = null 59 | for (int i = 0; i < variant.sourceSets.size(); i++) { 60 | def sourceSet = variant.sourceSets[i] 61 | if (sourceSet.manifestFile.exists()) { 62 | def parser = new XmlParser() 63 | Node node = parser.parse(sourceSet.manifestFile) 64 | packageName = node.attribute("package") 65 | if (packageName != null) { 66 | break 67 | } 68 | } 69 | } 70 | return packageName 71 | } 72 | } -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/task/AndroidJunkCodeTask.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.task 2 | 3 | import cn.hx.plugin.junkcode.ext.JunkCodeConfig 4 | import cn.hx.plugin.junkcode.template.ManifestTemplate 5 | import cn.hx.plugin.junkcode.template.ResTemplate 6 | import com.squareup.javapoet.ClassName 7 | import com.squareup.javapoet.JavaFile 8 | import com.squareup.javapoet.MethodSpec 9 | import com.squareup.javapoet.TypeSpec 10 | import groovy.text.GStringTemplateEngine 11 | import org.gradle.api.DefaultTask 12 | import org.gradle.api.tasks.Input 13 | import org.gradle.api.tasks.Nested 14 | import org.gradle.api.tasks.OutputDirectories 15 | import org.gradle.api.tasks.TaskAction 16 | 17 | import javax.lang.model.element.Modifier 18 | 19 | class AndroidJunkCodeTask extends DefaultTask { 20 | 21 | static def random = new Random() 22 | 23 | static abc = "abcdefghijklmnopqrstuvwxyz".toCharArray() 24 | 25 | @Nested 26 | JunkCodeConfig config = new JunkCodeConfig() 27 | 28 | @Input 29 | String manifestPackageName = "" 30 | 31 | @OutputDirectories 32 | File outDir 33 | 34 | @TaskAction 35 | void execute() { 36 | if (outDir.exists()) { 37 | outDir.deleteDir() 38 | } 39 | //通过成类 40 | generateClasses() 41 | //生成资源 42 | generateRes() 43 | } 44 | 45 | /** 46 | * 生成java代码和AndroidManifest.xml 47 | */ 48 | void generateClasses() { 49 | def javaDir = new File(outDir, "java") 50 | for (int i = 0; i < config.packageCount; i++) { 51 | String packageName = config.packageBase + "." + generateName(i) 52 | //生成Activity 53 | for (int j = 0; j < config.activityCountPerPackage; j++) { 54 | def activityPreName = generateName(j) 55 | generateActivity(packageName, activityPreName) 56 | } 57 | //生成其它类 58 | for (int j = 0; j < config.otherCountPerPackage; j++) { 59 | def className = generateName(j).capitalize() 60 | def typeBuilder = TypeSpec.classBuilder(className) 61 | for (int k = 0; k < config.methodCountPerClass; k++) { 62 | def methodName = generateName(k) 63 | def methodBuilder = MethodSpec.methodBuilder(methodName) 64 | generateMethods(methodBuilder) 65 | typeBuilder.addMethod(methodBuilder.build()) 66 | } 67 | def fileBuilder = JavaFile.builder(packageName, typeBuilder.build()) 68 | fileBuilder.build().writeTo(javaDir) 69 | } 70 | } 71 | } 72 | 73 | /** 74 | * 生成随机方法 75 | * @param methodBuilder 76 | */ 77 | static void generateMethods(MethodSpec.Builder methodBuilder) { 78 | switch (random.nextInt(5)) { 79 | case 0: 80 | methodBuilder.addStatement("long now = \$T.currentTimeMillis()", System.class) 81 | .beginControlFlow("if (\$T.currentTimeMillis() < now)", System.class) 82 | .addStatement("\$T.out.println(\$S)", System.class, "Time travelling, woo hoo!") 83 | .nextControlFlow("else if (\$T.currentTimeMillis() == now)", System.class) 84 | .addStatement("\$T.out.println(\$S)", System.class, "Time stood still!") 85 | .nextControlFlow("else") 86 | .addStatement("\$T.out.println(\$S)", System.class, "Ok, time still moving forward") 87 | .endControlFlow() 88 | break 89 | case 1: 90 | methodBuilder.addCode("" 91 | + "int total = 0;\n" 92 | + "for (int i = 0; i < 10; i++) {\n" 93 | + " total += i;\n" 94 | + "}\n") 95 | break 96 | case 2: 97 | methodBuilder.beginControlFlow("try") 98 | .addStatement("throw new Exception(\$S)", "Failed") 99 | .nextControlFlow("catch (\$T e)", Exception.class) 100 | .addStatement("throw new \$T(e)", RuntimeException.class) 101 | .endControlFlow() 102 | break 103 | case 3: 104 | methodBuilder.returns(Date.class) 105 | .addStatement("return new \$T()", Date.class) 106 | break 107 | case 4: 108 | methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC) 109 | .returns(void.class) 110 | .addParameter(String[].class, "args") 111 | .addStatement("\$T.out.println(\$S)", System.class, "Hello") 112 | break 113 | default: 114 | methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC) 115 | .returns(void.class) 116 | .addParameter(String[].class, "args") 117 | .addStatement("\$T.out.println(\$S)", System.class, "Hello") 118 | } 119 | } 120 | 121 | /** 122 | * 生成Activity 123 | * @param packageName 124 | * @param activityPreName 125 | */ 126 | void generateActivity(String packageName, String activityPreName) { 127 | def javaDir = new File(outDir, "java") 128 | def className = activityPreName.capitalize() + "Activity" 129 | def layoutName = "${config.resPrefix.toLowerCase()}${packageName.replace(".", "_")}_activity_${activityPreName}" 130 | generateLayout(layoutName) 131 | def typeBuilder = TypeSpec.classBuilder(className) 132 | typeBuilder.superclass(ClassName.get("android.app", "Activity")) 133 | //onCreate方法 134 | def bundleClassName = ClassName.get("android.os", "Bundle") 135 | typeBuilder.addMethod(MethodSpec.methodBuilder("onCreate") 136 | .addAnnotation(Override.class) 137 | .addModifiers(Modifier.PROTECTED) 138 | .addParameter(bundleClassName, "savedInstanceState") 139 | .addStatement("super.onCreate(savedInstanceState)") 140 | .addStatement("setContentView(\$T.layout.${layoutName})", ClassName.get(manifestPackageName, "R")) 141 | .build()) 142 | //其它方法 143 | for (int j = 0; j < config.methodCountPerClass; j++) { 144 | def methodName = generateName(j) 145 | def methodBuilder = MethodSpec.methodBuilder(methodName) 146 | generateMethods(methodBuilder) 147 | typeBuilder.addMethod(methodBuilder.build()) 148 | } 149 | def fileBuilder = JavaFile.builder(packageName, typeBuilder.build()) 150 | fileBuilder.build().writeTo(javaDir) 151 | addToManifestByFileIo(className, packageName) 152 | } 153 | 154 | /** 155 | * 生成资源文件 156 | */ 157 | void generateRes() { 158 | //生成drawable 159 | for (int i = 0; i < config.drawableCount; i++) { 160 | def drawableName = "${config.resPrefix.toLowerCase()}${generateName(i)}" 161 | generateDrawable(drawableName) 162 | } 163 | //生成string 164 | for (int i = 0; i < config.stringCount; i++) { 165 | def name = "${config.resPrefix.toLowerCase()}${generateName(i)}" 166 | def value = name 167 | addStringByFileIo(name, value) 168 | } 169 | } 170 | 171 | /** 172 | * 生成layout 173 | * @param layoutName 174 | */ 175 | void generateDrawable(String drawableName) { 176 | def drawableFile = new File(outDir, "res/drawable/${drawableName}.xml") 177 | if (!drawableFile.getParentFile().exists()) { 178 | drawableFile.getParentFile().mkdirs() 179 | } 180 | if (!drawableFile.exists()) { 181 | drawableFile.createNewFile() 182 | } 183 | FileWriter writer 184 | try { 185 | writer = new FileWriter(drawableFile) 186 | def template = ResTemplate.DRAWABLE 187 | writer.write(template.toString()) 188 | } catch (Exception e) { 189 | e.printStackTrace() 190 | } finally { 191 | if (writer != null) { 192 | writer.close() 193 | } 194 | } 195 | } 196 | 197 | 198 | /** 199 | * 生成layout 200 | * @param layoutName 201 | */ 202 | void generateLayout(String layoutName) { 203 | def layoutFile = new File(outDir, "res/layout/${layoutName}.xml") 204 | if (!layoutFile.getParentFile().exists()) { 205 | layoutFile.getParentFile().mkdirs() 206 | } 207 | if (!layoutFile.exists()) { 208 | layoutFile.createNewFile() 209 | } 210 | FileWriter writer 211 | try { 212 | writer = new FileWriter(layoutFile) 213 | def template = ResTemplate.LAYOUT_TEMPLATE 214 | writer.write(template.toString()) 215 | } catch (Exception e) { 216 | e.printStackTrace() 217 | } finally { 218 | if (writer != null) { 219 | writer.close() 220 | } 221 | } 222 | } 223 | 224 | 225 | /** 226 | * 通过文件读写流的方式将新创建的Activity加入清单文件 227 | * 228 | * @param activityName 229 | * @param packageName 230 | */ 231 | void addToManifestByFileIo(String activityName, String packageName) { 232 | def manifestFile = new File(outDir, "AndroidManifest.xml") 233 | if (!manifestFile.getParentFile().exists()) { 234 | manifestFile.getParentFile().mkdirs() 235 | } 236 | if (!manifestFile.exists()) { 237 | def template = ManifestTemplate.TEMPLATE 238 | FileWriter writer 239 | try { 240 | writer = new FileWriter(manifestFile) 241 | writer.write(template.toString()) 242 | } catch (Exception e) { 243 | e.printStackTrace() 244 | } finally { 245 | if (writer != null) { 246 | writer.close() 247 | } 248 | } 249 | } 250 | FileReader reader 251 | FileWriter writer 252 | try { 253 | reader = new FileReader(manifestFile) 254 | StringBuilder sb = new StringBuilder() 255 | // 每一行的内容 256 | String line = "" 257 | while ((line = reader.readLine()) != null) { 258 | // 找到application节点的末尾 259 | if (line.contains("")) { 260 | // 在application节点最后插入新创建的activity节点 261 | def binding = [ 262 | packageName : packageName, 263 | activityName: activityName, 264 | ] 265 | def template = makeTemplate(ManifestTemplate.ACTIVITY_NODE, binding) 266 | sb.append(template.toString() + "\n") 267 | } 268 | sb.append(line + "\n") 269 | } 270 | String content = sb.toString() 271 | writer = new FileWriter(manifestFile) 272 | writer.write(content) 273 | } catch (Exception e) { 274 | e.printStackTrace() 275 | } finally { 276 | if (reader != null) { 277 | reader.close() 278 | } 279 | if (writer != null) { 280 | writer.close() 281 | } 282 | } 283 | } 284 | 285 | /** 286 | * 将string写入strings.xml 287 | * @param name 288 | * @param value 289 | */ 290 | void addStringByFileIo(String name, String value) { 291 | //生成string 292 | def stringFile = new File(outDir, "res/values/strings.xml") 293 | if (!stringFile.getParentFile().exists()) { 294 | stringFile.getParentFile().mkdirs() 295 | } 296 | if (!stringFile.exists()) { 297 | stringFile.createNewFile() 298 | FileWriter writer 299 | try { 300 | writer = new FileWriter(stringFile) 301 | def template = ResTemplate.TEMPLATE 302 | writer.write(template.toString()) 303 | } catch (Exception e) { 304 | e.printStackTrace() 305 | } finally { 306 | if (writer != null) { 307 | writer.close() 308 | } 309 | } 310 | } 311 | FileReader reader 312 | FileWriter writer 313 | try { 314 | reader = new FileReader(stringFile) 315 | StringBuilder sb = new StringBuilder() 316 | // 每一行的内容 317 | String line = "" 318 | while ((line = reader.readLine()) != null) { 319 | // 找到resources节点的末尾 320 | if (line.contains("")) { 321 | // 在resources节点最后插入新创建的string节点 322 | def binding = [ 323 | stringName : name, 324 | stringValue: value, 325 | ] 326 | def template = makeTemplate(ResTemplate.STRING_NODE, binding) 327 | sb.append(template.toString() + "\n") 328 | } 329 | sb.append(line + "\n") 330 | } 331 | String content = sb.toString() 332 | writer = new FileWriter(stringFile) 333 | writer.write(content) 334 | } catch (Exception e) { 335 | e.printStackTrace() 336 | } finally { 337 | if (reader != null) { 338 | reader.close() 339 | } 340 | if (writer != null) { 341 | writer.close() 342 | } 343 | } 344 | } 345 | 346 | /** 347 | * 加载模板 348 | * 349 | * @param template 350 | * @param binding 351 | * @return 352 | */ 353 | static def makeTemplate(def template, def binding) { 354 | def engine = new GStringTemplateEngine() 355 | return engine.createTemplate(template).make(binding) 356 | } 357 | 358 | /** 359 | * 生成名称 360 | * @param index 361 | * @return 362 | */ 363 | static String generateName(int index) { 364 | def sb = new StringBuffer() 365 | int temp = index 366 | while (temp >= 0) { 367 | sb.append(abc[temp % abc.size()]) 368 | temp = temp / abc.size() 369 | if (temp == 0) { 370 | temp = -1 371 | } 372 | } 373 | sb.append(index.toString()) 374 | return sb.toString() 375 | } 376 | } -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/template/ManifestTemplate.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.template 2 | 3 | class ManifestTemplate { 4 | static final def TEMPLATE = ''' 5 | 6 | 7 | ''' 8 | 9 | static final def ACTIVITY_NODE = ''' 10 | 11 | ''' 12 | } -------------------------------------------------------------------------------- /library/src/main/groovy/cn/hx/plugin/junkcode/template/ResTemplate.groovy: -------------------------------------------------------------------------------- 1 | package cn.hx.plugin.junkcode.template 2 | 3 | class ResTemplate { 4 | static final def TEMPLATE = ''' 5 | ''' 6 | 7 | static final def DRAWABLE = ''' 13 | 18 | 19 | 25 | 28 | 31 | 32 | 33 | 34 | 40 | ''' 41 | 42 | 43 | static final def STRING_NODE = ''' ${stringValue}''' 44 | 45 | 46 | static final def LAYOUT_TEMPLATE = ''' 47 | 51 | 52 | 57 | ''' 58 | } -------------------------------------------------------------------------------- /library/src/main/resources/META-INF/gradle-plugins/android-junk-code.properties: -------------------------------------------------------------------------------- 1 | implementation-class=cn.hx.plugin.junkcode.plugin.AndroidJunkCodePlugin -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':library' 2 | include ':app' 3 | rootProject.name = "AndroidJunkCode" --------------------------------------------------------------------------------