问题
I'd like to create a Gradle task that computes the classes.dex
CRC, then writes the resulting value into a resource string. This value will be checked at runtime to determine whether the APK has been tampered or not. The problem is that beginning with Gradle plugin 1.4.+ it is not possible to access the dex task anymore. Instead, we should use Transform API. I found very little documentation about Gradle tasks in the Android environment, so I would ask a few questions:
- What's the Gradle task that deals with the
classes.dex
file? - How should the Transform work with this task?
I've seen lots of threads about this argument, but none of these have a working solution. Thanks in advance!
回答1:
According to Xavier Ducrohet:
You have to build twice. classes.dex contains R.class which is generate from the res compilation. So by the time you're computing the CRC32 it's too late to put it in.
In general you really shouldn't be modifying the model during task execution. In fact, Gradle will introduce task parallelization that really will require to not touch the model when the task are running. So we're going to (try to) fix this by making it impossible to do this. I just filed > https://code.google.com/p/android/issues/detail?id=82574
So I would do the following: - in the evaluation phase of your project, read a file that contains the CRC and set it as a resources. Something like this (using Guava):
android.applicationVariants.all { variant -> variant.resValue "string", "CRC", com.google.common.io.Files.toString(file("$buildDir/intermediates/checksum/$variant.dirName/classes.crc32"), Charsets.UTF_8)
}
- setup a task that creates the file that contains the CRC32.
android.applicationVariants.all { variant -> variant,outputs.each { // create the task here. it depends on the dex task, and make the outputs.packageApplication task depend on it. } }
Note: this is not enough. What you know need to do is ensure that if the newly computed CRC32 is different than the current file, the build breaks, forcing you to build a 2nd time. This way you have the two cases: - CRC32 file is missing or the content is incorrect. You compute the new CRC32, put it in the file and fail the build forcing to build again with this new value. - CRC32 is already valid, which mean the resource contains the right value, the task does nothing more and the build continues.
https://groups.google.com/d/msg/adt-dev/W2aYLBSeGUE/fzOqyH8YibQJ
来源:https://stackoverflow.com/questions/38532628/gradle-task-for-classes-dex-crc-calculation