简体   繁体   中英

Using proguard in java modules Android Studio

I'm attempting to use proguard in a build.gradle file for a java module on Android Studio and I need to ofuscate the resulting source code but when I use proguard as I used to in other projects the build task fails. Below I show what I've trying to do and the error:

import proguard.gradle.ProGuardTask

apply plugin: 'java'

task proguardFiles(dependsOn: compileJava, type: ProGuardTask) {
   //
}


Error:Cause: startup failed:
script '...Path\build.gradle': 1: unable to resolve class proguard.gradle.ProGuardTask
@ line 1, column 1.
import proguard.gradle.ProGuardTask
^

1 error

Any ideas about the solution?

I found the solution to my own question, I hope this be helpful for someone who need it.

Include at top of gradle file:

import proguard.gradle.ProGuardTask

in other place into the same file or project configuration (gradle file) put this:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'net.sf.proguard:proguard-gradle:5.2.1'
    }
}

finally define your custom proguardTask:

task proguardFiles(type: ProGuardTask, dependsOn: compileJava) {
    printmapping "$buildDir/outputs/mapping/mapping.txt"
    configuration 'proguard-rules.pro'

    libraryjars files(configurations.compile.findAll {}.collect())

    injars sourceSets.main.output

    outjars "$buildDir/libs/myJarName-${version}.jar"
}

and it should work!!!

If you want to proguard your java lib without copying jar from its output folder to your android module lib folder, here's one workable solution:

import proguard.gradle.ProGuardTask

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'net.sf.proguard:proguard-gradle:5.3.3'
    }
}

task proguardFiles(type: ProGuardTask, dependsOn: compileJava) {
    // make jar task wait for proguardFiles task finish
    tasks.jar.dependsOn.add(proguardFiles)

    println "proguarding"

    printmapping "$buildDir/mapping.txt"
    configuration 'proguard-rules.pro'
    libraryjars files(configurations.compile.findAll {}.collect())
    injars sourceSets.main.output

    // files output type, don't use jar
    outjars "$buildDir/libs/${project.name}"
    delete "$buildDir/libs/${project.name}"

    doLast {
        println "copying product:${sourceSets.main.output.classesDir}"

        // replace orginal class files with proguarded class files
        delete "${sourceSets.main.output.classesDir}"
        copy {
            from "$buildDir/libs/${project.name}"
            into "${sourceSets.main.output.classesDir}"
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM