Android Studio gradle conflict with dependency for app and test app versions

As an Android developer, high chances that you are using Android Studio for development and gradle for dependency management. Gradle is great, much like cocoapod in iOS world, it helps you save tons of effort and all the hassle of managing libraries/dependencies. But once in a while you may bump into some issues with gradle, like the one I’m facing below, and it took me a few hours to resolve it. Hope this sharing may help someone facing the same issue.

So the issue is I updated my android project’s targetSdkVersion to 26 (Android Oreo), also updated buildToolsVersion and supportLibraryVersion properly to version 26. But then I hit some big issues with limitations of Oreo. To name some: (full changes log you can see here at Android Developer page

  • The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.
  • Notifications must be in a channel, otherwise they cannot be displayed on screen. You can debug which notifications violating this new rule by enabling Show notifications channel warnings in Developer options in Settings.

Sleep Detection and notifications are 2 very crucial features of my app. I understand I need to do some changes to fully support Oreo, but given tight schedule I have to make a decision to ignore Oreo for now. So what I did was reverting targetSdkVersion back to 25 , also set buildToolsVersion = ‘25.0.3’ and supportLibraryVersion = '25.4.0' . Things are perfectly fine, my app can call startService() from background, and notifications are working great. But I get this annoying gradle warning saying:

Warning:Conflict with dependency ‘com.android.support:support-annotations’. Resolved versions for app (26.0.2) and test app (25.4.0) differ.

Clearly the message is saying that I’m using different versions of the same dependency in main app (26.0.2) and test app (25.4.0), which is super weird as no where in my gradle file is mentioning 26.0.2 . I thought it’s the cache that messes up, I even did Invalidate Caches/Restart... in Android Studio but still no luck. Some google searches suggest some ways like hard-coding version of the support-annotations dependency, tried it also, still didn’t work.

Finally the gradle strategy was the only solution that works for me. Add these lines to your dependencies block in your app build.gradle file:

configurations.all { 
 resolutionStrategy {
 force “com.android.support:support-annotations:$rootProject.ext.supportLibraryVersion”
 }
 }

This will force the troublesome dependency to use the version mentioned in the force command, no matter what it is the main app or test app or any modules.

Simple fix but it took me 1–2 hours to figure it out. Hope this help save few hours people out there for this same issue.