Gradle error during android building

After migrating from 2017.2.2p4 to 2018.3b5 during android build process i faced with gradle error

CommandInvokationFailure: Gradle build failed.
C:/Program Files/Java/jdk1.8.0_141\bin\java.exe -classpath "C:\Program Files\Unity 2018.3.0b5\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-4.6.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

stderr[

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Unity_Projects\JamTracks_2018.3b\Temp\gradleOut\build.gradle' line: 19

* What went wrong:
A problem occurred evaluating root project 'gradleOut'.
> Failed to apply plugin [id 'com.android.application']
   > Gradle version 2.10 is required. Current version is 4.6. If using the gradle wrapper, try editing the distributionUrl in C:\Unity_Projects\JamTracks_2018.3b\Temp\gradleOut\gradle\wrapper\gradle-wrapper.properties to gradle-2.10-all.zip

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s
]
stdout[
Starting a Gradle Daemon (subsequent builds will be faster)
]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <480e50343593457c94864bd38c09a2ca>:0)
Rethrow as GradleInvokationException: Gradle build failed
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <480e50343593457c94864bd38c09a2ca>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Used gradle file

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
    }
}

allprojects {
   repositories {
      flatDir {
        dirs 'libs'
      }
   }
}

apply plugin: 'com.android.application'

dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:multidex:1.0.1'
**DEPS**}

android {
    compileSdkVersion **APIVERSION**
    buildToolsVersion '**BUILDTOOLS**'

    defaultConfig {
        targetSdkVersion **TARGETSDKVERSION**
        applicationId '**APPLICATIONID**'
        multiDexEnabled true
       
        versionCode 25
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        noCompress '.unity3d', '.ress', '.resource', '.obb'
    }

**SIGN**
    buildTypes {
          debug {
             //minifyEnabled **MINIFY_DEBUG**
             //useProguard **PROGUARD_DEBUG**
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
              jniDebuggable true
          }
          release {
             //minifyEnabled **MINIFY_RELEASE**
             //useProguard **PROGUARD_RELEASE**
              proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
              **SIGNCONFIG**
          }
    }


    splits {
       
            // Configures multiple APKs based on ABI.
            abi {
       
              // Enables building multiple APKs per ABI.
              enable true
       
              // By default all ABIs are included, so use reset() and include to specify that we only
              // want APKs for x86 and x86_64.
       
              // Resets the list of ABIs that Gradle should create APKs for to none.
              reset()
       
              // Specifies a list of ABIs that Gradle should create APKs for.
              include "armeabi-v7a"
              //include "x86"
       
              // Specifies that we do not want to also generate a universal APK that includes all ABIs.
              universalApk false
            }
          }
}

// Map for the version code that gives each ABI a value.
ext.abiCodes = ['armeabi-v7a':1, x86:2, x86_64:3]

// For per-density APKs, create a similar map like this:
// ext.densityCodes = ['mdpi': 1, 'hdpi': 2, 'xhdpi': 3]

import com.android.build.OutputFile

// For each APK output variant, override versionCode with a combination of
// ext.abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
android.applicationVariants.all { variant ->

  // Assigns a different version code for each output APK
  // other than the universal APK.
  variant.outputs.each { output ->

    // Stores the value of ext.abiCodes that is associated with the ABI for this variant.
    def baseAbiVersionCode =
            // Determines the ABI for this variant and returns the mapped value.
            project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))

    // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
    // the following code does not override the version code for universal APKs.
    // However, because we want universal APKs to have the lowest version code,
    // this outcome is desirable.
    if (baseAbiVersionCode != null) {

      // Assigns the new version code to versionCodeOverride, which changes the version code
      // for only the output APK, not for the variant itself. Skipping this step simply
      // causes Gradle to use the value of variant.versionCode for the APK.
      output.versionCodeOverride =
              baseAbiVersionCode * 1000 + variant.versionCode
    }
  }
}

When updating between major versions of Unity, you should compare your custom Gradle file with Unity’s Gradle template file because Unity will sometimes change important details and you’ll need to keep up-to-date.

For example, below is mainTemplate.gradle file that ships with Unity 2018.3.0b5. On Mac that can be found at /Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/GradleTemplates/mainTemplate.gradle (not sure where it is on Windows but should be similar).

You’ll see a number of differences to your Gradle file, most notably for your error are the differences in the buildscript and allprojects sections.

// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

buildscript {
    repositories {
        jcenter()
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0-alpha15'
**BUILD_SCRIPT_DEPS**}
}

allprojects {
    repositories {
        jcenter()
        google()
        flatDir {
            dirs 'libs'
        }
    }
}

apply plugin: 'com.android.application'
**APPLY_PLUGINS**

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
**DEPS**}

android {
    compileSdkVersion **APIVERSION**
    buildToolsVersion '**BUILDTOOLS**'

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion **MINSDKVERSION**
        targetSdkVersion **TARGETSDKVERSION**
        applicationId '**APPLICATIONID**'
        ndk {
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        noCompress = ['.unity3d', '.ress', '.resource', '.obb'**STREAMING_ASSETS**]
    }**SIGN**

    buildTypes {
        debug {
            minifyEnabled **MINIFY_DEBUG**
            useProguard **PROGUARD_DEBUG**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
            jniDebuggable true
        }
        release {
            minifyEnabled **MINIFY_RELEASE**
            useProguard **PROGUARD_RELEASE**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD****SIGNCONFIG**
        }
    }**PACKAGING_OPTIONS****SPLITS**
**BUILT_APK_LOCATION**
    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = false
        }
        abi {
            enableSplit = true
        }
    }
}**SPLITS_VERSION_CODE****REPOSITORIES****SOURCE_BUILD_SETUP**
2 Likes

After all changes i’ve got this

FileNotFoundException: Temp\gradleOut\build\outputs\apk\release\gradleOut-release.apk does not exist
System.IO.File.Move (System.String sourceFileName, System.String destFileName) (at <f2e6809acb14476a81f399aeb800f8f2>:0)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <37ed2f677a93461fa013cddc2cc869d2>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <37ed2f677a93461fa013cddc2cc869d2>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <37ed2f677a93461fa013cddc2cc869d2>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <37ed2f677a93461fa013cddc2cc869d2>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:287)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Hey,

ScottyB is correct, we’ve updated the gradle build template quite a bit between those versions, so your custom template has to be updated to match the new version. The last error you’ve posted seems to lack a bit of information - was there any other output in the console? How does your custom build template look like now?

I’m also facing the similar problem.
I have swapped the lib folder of gradle in Unity playbackEngine folder,
(to the gradle 4.6 version according to this advice :
Change version of Gradle to 4.6 - Questions & Answers - Unity Discussions )
and override the mainTemplate.gradle and libTemplate.gradle with this files.
(https://github.com/deltaDNA/unity-sdk/tree/master/Assets/Plugins/Android)
and now I’m seeing the same error

FileNotFoundException: Temp\gradleOut\build\outputs\apk\gradleOut-debug.apk does not exist
System.IO.File.Move (System.String sourceFileName, System.String destFileName) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:318)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:186)

what can I do???
Should I export project and modify it with Android Studio?
I can, but I would like to Build & Run in Unity…
(I’m Unity 5.6.5f)

2 Likes