Skip to content

Instantly share code, notes, and snippets.

@clayburn
Last active May 14, 2022
Embed
What would you like to do?
Copy Apk
//see: https://github.com/android/gradle-recipes/blob/master/Groovy/workerEnabledTransformation/app/build.gradle
import com.android.build.api.artifact.ArtifactTransformationRequest
import com.android.build.api.artifact.SingleArtifact
import com.android.build.api.variant.BuiltArtifact
import com.android.build.api.variant.BuiltArtifacts
import com.android.build.api.variant.BuiltArtifactsLoader
import javax.inject.Inject
import java.nio.file.Files
interface WorkItemParameters extends WorkParameters {
RegularFileProperty getInputApkFile()
RegularFileProperty getOutputApkFile()
}
abstract class WorkItem implements WorkAction<WorkItemParameters> {
WorkItemParameters workItemParameters
@Inject
WorkItem(WorkItemParameters parameters) {
this.workItemParameters = parameters
}
void execute() {
workItemParameters.getOutputApkFile().get().getAsFile().delete()
Files.copy(
workItemParameters.getInputApkFile().getAsFile().get().toPath(),
workItemParameters.getOutputApkFile().get().getAsFile().toPath())
}
}
abstract class CopyApksTask extends DefaultTask {
@Internal
WorkerExecutor workers
@Inject
CopyApksTask(WorkerExecutor workerExecutor) {
this.workers = workerExecutor
}
@InputFiles
abstract DirectoryProperty getApkFolder()
@OutputDirectory
abstract DirectoryProperty getOutFolder()
@Internal
abstract Property<ArtifactTransformationRequest<CopyApksTask>> getTransformationRequest()
@TaskAction
void taskAction() {
transformationRequest.get().submit(this, workers.noIsolation(), WorkItem, { BuiltArtifact builtArtifact, Directory outputLocation, WorkItemParameters param ->
File inputFile = new File(builtArtifact.outputFile)
param.getInputApkFile().set(inputFile)
param.getOutputApkFile().set(new File(outputLocation.asFile, inputFile.name))
param.getOutputApkFile().get().getAsFile()
})
}
}
androidComponents {
onVariants(selector().all(), { variant ->
TaskProvider copyApksProvider = tasks.register('copy' + variant.getName() + 'Apks', CopyApksTask)
ArtifactTransformationRequest request =
variant.artifacts.use(copyApksProvider)
.wiredWithDirectories(
{ it.getApkFolder() },
{ it.getOutFolder()})
.toTransformMany(SingleArtifact.APK.INSTANCE)
copyApksProvider.configure {
it.transformationRequest.set(request)
it.outFolder.set(project.layout.buildDirectory.dir("my-custom-output-directory"))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment