MichD

 

Gradle Android: API 'variant.getX()' is obsolete

A deprecation warning I got when trying to add something to our Android gradle build script proved hard to fix, so I’m documenting my findings here.

These are the full messages I’d get; there are similar ones for other tasks you want to tie into.

WARNING: API ‘variant.getMergeResources()’ is obsolete and has been replaced with ‘variant.getMergeResourcesProvider()’. It will be removed in version 5.0 of the Android Gradle plugin.

WARNING: API ‘variant.getProcessResources()’ is obsolete and has been replaced with ‘variant.getProcessResourcesProvider()’. It will be removed in version 5.0 of the Android Gradle plugin.

These warnings would show up in the build output when trying to do something like the following:

android.applicationVariants.all { variant ->
    variant.mergeResources.doLast {
        // Some code to execute after the "merge resources" task of the build
    }
}

Given that the warning stated to use getMergeResourcesProvider instead, I naively replaced mergeResources with mergeResourcesProvider, which didn’t work, as it has no doLast field. At this point I should mention that Android Studio was not at all helping out with what fields were available. I could find no actual documentation on any of these APIs, so I had to do extensive digging.

Solution

To keep it brief, use the following:

android.applicationVariants.all { variant ->
    variant.mergeResourcesProvider.getOrNull()?.doLast {
        // Some code to execute after the "merge resources" task of the build,
        // if the "merge resources" task is being run
    }
}

Similarly, for other tasks you may want to tie into:

variant.<task>.doLast

becomes

variant.<task>Provider.getOrNull()?.doLast

Where I found it

  1. I found the source code of the android gradle plugin with the help of this: albert c braun’s answer to “Source code of Google’s Gradle Plugin for building Android” on Stack Overflow. It’s also on googlesource.com but that site, inexplicably, doesn’t let you browse the source.
  2. With the help of a bit of grep I found the file com/android/build/gradle/internal/api/BaseVariantImpl.java
  3. In there I found the deprecated getMergeResources() and saw how it accessed the task the way I demonstrated above

All the answers about similar queries I saw when searching this deprecation warning were about instances where someone was using a library that needed updating, so they never went into exactly what should be done. I suppose it’s fairly uncommon to tie into the build process to do something custom.

For corrections / comments, please reach out to me on Twitter.