I have a java Android project and I am trying to include Kotlin/Convert some of the java classes to Kotlin.
Project's build.gradle:
Here I have introduced a variable for Kotlin version 1.6.10 and kotlin gradle plugin.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
import com.tcs.dev.Repo
import org.gradle.wrapper.SystemPropertiesHandler
buildscript {
ext.kotlin_version = '1.6.10'
// load local.properties file like gradle.properties
System.getProperties().putAll(SystemPropertiesHandler.getSystemProperties(file('local.properties')))
Properties properties = new Properties()
if (file("local.properties").exists()) {
properties.load(file('local.properties').newDataInputStream())
}
if (project.hasProperty('propfile')) {
properties.load(file(propfile).newDataInputStream())
}
properties.each { k, v -> ext[k] = v }
repositories {
google()
maven Repo.config(project)
maven { url 'https://jitpack.io' }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" } // For Spoon snapshot, until 2.0.0 is released
jcenter()
}
dependencies {
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.google.gms:google-services:4.3.10'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
App's build.gradle:
Here I have introduced the Kotlin plugin and two more Kotlin libraries in the implementation section.
import com.tcs.dev.BuildVars
import com.tcs.dev.FileExtension
import com.tcs.dev.PropertiesFile
import com.tcs.dev.Repo
import com.tcs.dev.Shell
import com.tcs.dev.Version
import java.nio.file.Files
import java.nio.file.Paths
import java.util.regex.Pattern
buildscript {
// Items referenced both in and outside of the buildscript block
ext {
buildToolsDir = System.env.get('HOME') + "/build_tools"
localProperties = new File(rootProject.projectDir, "local.properties")
}
// SDK - needs to be done by buildscript because the android-sdk-manager plugin requires it on apply
def androidSdkName = getProperty('systemProp.tcs.dev.android.sdk.name')
def androidSdkVersion = getProperty('systemProp.tcs.dev.android.sdk.version')
def androidSdkClassifier = "darwin-x86_64"
def androidSdkExt = "tgz"
repositories {
jcenter()
google()
maven Repo.config(project)
}
dependencies {
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
classpath group: 'com.google', name: androidSdkName,
version: androidSdkVersion, ext: androidSdkExt, classifier: androidSdkClassifier
}
PropertiesFile.addOrChangeKey(project.localProperties, "sdk.dir", androidSdkDir)
// This should already exist, but just in case not
FileExtension.mkdirs(project.buildToolsDir)
// Extract the Android SDK
if (! new File(sdkBomFile).exists()) {
def sdkFile = sprintf("%s-%s-%s.%s", androidSdkName, androidSdkVersion, androidSdkClassifier, androidSdkExt)
def sdkFullFile = buildscript.configurations.classpath.files.find {
if (it.getName() == sdkFile) return it.getAbsoluteFile()
}
println "Extracting Android SDK"
def cmd = "tar -zxf ${sdkFullFile} -C ${project.buildToolsDir}"
def (exitValue, output) = Shell.shellCommandReturningExitValueAndOutput(cmd)
if (exitValue != 0) {
throw new Exception("Extract command exited with '${exitValue}': ${cmd}")
}
if (! new File(sdkBomFile).exists()) {
throw new Exception("Extract command did not create file '${sdkBomFile}': ${cmd}")
}
println "Accepting license agreements"
cmd = "yes | ${androidSdkDir}/tools/bin/sdkmanager --sdk_root=${androidSdkDir} --licenses"
(exitValue, output) = Shell.shellCommandReturningExitValueAndOutput(cmd)
}
}
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.firebase.crashlytics'
id 'com.google.gms.google-services'
}
// NDK
def androidNdkName = getProperty('systemProp.tcs.dev.android.ndk.name')
def androidNdkVersion = getProperty('systemProp.tcs.dev.android.ndk.version')
def androidNdkDir = sprintf("%s/%s-%s", project.buildToolsDir, androidNdkName, androidNdkVersion)
def androidNdkInstalled = {
return new File(androidNdkDir, 'ndk-build').exists()
}
// AVD
def androidAvdName = getProperty('systemProp.tcs.dev.android.avd.name')
def androidAvdVersion = getProperty('systemProp.tcs.dev.android.avd.version')
def androidAvdDir = sprintf("%s/%s-%s", project.buildToolsDir, androidAvdName, androidAvdVersion)
def androidAvdInstalled = {
return new File(androidAvdDir, "Nexus_9_API_${androidAvdVersion}.ini").exists()
}
[graphicsLibVersion:graphicsLibVersion, serializableLibVersion:serializableLibVersion].each { k, v ->
if (!v.startsWith(Version.projectVersion())) {
logger.warn "WARNING: ${k} ${v} does not match projectVersion ${Version.projectVersion()} please update"
}
}
def gitSha() {
return 'git rev-parse --short HEAD'.execute().text.trim()
}
configurations {
graphicsLib
eigen
generatedSource
manuallyEditedSourceDependencies
if (!androidNdkInstalled()) {
androidNdk
}
if (!androidAvdInstalled()) {
androidAvd
}
}
dependencies {
graphicsLib group: 'com.tcs', name: 'graphics-lib',
version: graphicsLibVersion, ext: 'tgz', classifier: 'sources'
generatedSource group: 'com.tcs', name: 'tcs-serializable-generator',
manuallyEditedSourceDependencies group: 'com.tcs', name: 'cppGraphicsDependencies',
version: cppGraphicsVersion, ext: 'tgz', classifier: 'sources'
if (!androidNdkInstalled()) {
androidNdk group: 'com.google', name: androidNdkName,
version: androidNdkVersion, ext: 'zip', classifier: 'darwin-x86_64'
}
if (!androidAvdInstalled()) {
androidAvd group: 'com.google', name: androidAvdName,
version: androidAvdVersion, ext: 'tgz', classifier: 'darwin-x86_64'
}
}
def minutesSinceEpoch() {
// This should produce unique values for > 4000 years
def minutes = new Date().time.intdiv(1000).intdiv(60).intdiv(30) * 30
Integer clamped = minutes & Integer.MAX_VALUE
return clamped
}
android {
compileSdkVersion 30
buildToolsVersion '30.0.0'
// Required for butterknife compatibility with androidx
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
defaultConfig {
applicationId = BuildVars.applicationId
minSdkVersion 21
targetSdkVersion 30
versionCode minutesSinceEpoch()
versionName "${Version.packageVersion()}"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
}
sourceSets.main {
// use the jni .so compiled from the manual ndk-build command'''
jniLibs.srcDirs = ['src/main/jniLibs/debug/lib', 'src/main/jniLibs/release/lib']
jni.srcDirs = [] //disable automatic ndk-build call
}
signingConfigs {
debug {
storeFile file("../tcs-debug.keystore")
storePassword "dummy1"
keyAlias "debug"
keyPassword "dummy1"
}
release {
storeFile file("../tcs-android.keystore")
storePassword project.properties.get("dummy2")
keyAlias "release"
keyPassword project.properties.get("dummy2")
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.release
}
debug {
signingConfig signingConfigs.debug
applicationIdSuffix ".debug"
jniDebuggable true
ext.setBuildConfigFieldWithDefault = { fieldName, value ->
if (project.hasProperty(fieldName)) {
value = project.properties.get(fieldName)
}
buildConfigField "String", fieldName, "\"$value\""
}
def testMap = []
if (project.findProperty('testStack') == "staging") {
testMap = [
'testServer' :'https://staging.dev.tcs.com/',
'testAsmBrokenTestDocId':'a63f4467861f1c54500afd9d',
'testAsmBrokenTestWsId' :'9b6b7102fe2578a1d683adf1',
'testAnonymousDocId' :'346fa02ef804498723df9b6e'
]
} else {
testMap = [
'testServer' :'https://demo-c.dev.tcs.com/',
]
}
printf("testMap is: ${testMap}\n")
testMap.each{ k, v -> setBuildConfigFieldWithDefault(k, v) }
setBuildConfigFieldWithDefault("testUsername", "androidtester3#test.tcs.com")
setBuildConfigFieldWithDefault("testPassword", "testPassword")
ext.enableCrashlytics = false
pseudoLocalesEnabled true
testCoverageEnabled true
}
}
project.gradle.taskGraph.whenReady {
connectedDebugAndroidTest {
ignoreFailures = true
}
}
packagingOptions {
exclude 'META-INF/rxjava.properties'
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'LICENSE.txt'
doNotStrip "*/armeabi/*.so"
doNotStrip "*/armeabi-v7a/*.so"
doNotStrip "*/x86/*.so"
}
dexOptions {
javaMaxHeapSize "2g"
}
applicationVariants.all { variant ->
variant.mergeAssetsProvider.get().dependsOn(extractShaders)
}
lintOptions {
disable 'MissingTranslation', 'ExtraTranslation', 'NotSibling'
}
}
android.applicationVariants.all { variant ->
def applicationId = variant.applicationId as String
//def adbPath = android.adbExe as String
def adbPath = "/platform-tools/adb"
def variantName = variant.name.capitalize()
String pd = projectDir as String
def adbPlus = pd + "/../buildSrc/adb+.sh"
def grantPermissionsTask = tasks.create("grant${variantName}Permissions") {
doLast {
"bash ${adbPlus} ${adbPath} ${applicationId} android.permission.READ_CONTACTS".execute()
"bash ${adbPlus} ${adbPath} ${applicationId} android.permission.WRITE_EXTERNAL_STORAGE".execute()
}
}
grantPermissionsTask.description = "Grants permissions on Marshmallow and later"
grantPermissionsTask.group = "extras"
}
tasks.whenTaskAdded { theTask ->
if (theTask.name.equals("compileReleaseJavaWithJavac")) {
theTask.dependsOn "ndkBuildRelease"
} else if (theTask.name.equals("compileDebugJavaWithJavac")) {
theTask.dependsOn "ndkBuildDebug"
}
}
def assetsDir = new File(projectDir, 'src/main/assets')
task createAssetsDir() {
doFirst {
FileExtension.mkdirs(assetsDir)
}
}
task extractEigen(type: Copy) {
description = 'Expand eigen files into $EIGEN_DIR'
from(tarTree(configurations.eigen.singleFile)) {
include '*/Eigen/*'
include '*/Eigen/src/**'
}
if (eigenVersion == '506565787cdc4') { // 3.1.2
into eigenDir
def root = Pattern.compile('.*/Eigen/')
eachFile {
it.mode |= 0220
it.path = it.path.replaceFirst(root, '')
}
} else {
into eigenDir
eachFile {
it.mode |= 0220
}
}
dirMode 0775
}
task extractShaders(type: Exec) {
dependsOn createAssetsDir
def wd = assetsDir
def extractDir = 'shaders'
def targetFile = 'shaders'
inputs.file configurations.graphicsLib.singleFile
// Ensure the shaders are extracted
outputs.upToDateWhen { false }
outputs.dir "${wd}/${extractDir}"
workingDir wd
commandLine 'tar', '-s', ",graphics-lib-${graphicsLibVersion}/${targetFile},${extractDir},", '-xzf', configurations.graphicsLib.singleFile, "graphics-lib-${graphicsLibVersion}/${targetFile}"
}
task extractGraphics(type: Exec) {
description = 'set property graphics.repo.dir if you want to use your own version of the graphics repo.' +
' e.g. put a line like this in local.properties: graphics.repo.dir=/Users/pkania/repos/master/graphics'
def wd = 'src/main/jni'
def extractDir = 'Graphics'
def targetFile = 'GraphicsLibrary'
def graphicsDir = "${wd}/${extractDir}"
// Ensure the graphics are extracted
outputs.upToDateWhen { false }
outputs.dir graphicsDir
workingDir wd
doFirst {
def path = Paths.get(graphicsDir)
if (Files.isSymbolicLink(path)) {
Files.delete(path)
}
}
def graphicsRepoDir = project.properties.get('graphics.repo.dir')
if (graphicsRepoDir) {
def script = """
if [ -d ${extractDir} ]; then
rm -rf ${extractDir}
fi
ln -sf ${graphicsRepoDir}/BTGraphicsLibrary ${extractDir}
"""
commandLine Shell.getShellCommandLine(script)
} else {
inputs.file configurations.graphicsLib.singleFile
commandLine 'tar', '-s', ",graphics-lib-${graphicsLibVersion}/${targetFile},${extractDir},", '-xzf', configurations.graphicsLib.singleFile, "graphics-lib-${graphicsLibVersion}/${targetFile}"
}
}
task getGeneratedSource(type:Exec) {
description = 'extract cppGraphics generated source'
dependsOn extractGraphics
def tarFile = configurations.generatedSource.singleFile.path
inputs.file tarFile
workingDir 'src/main/jni'
// Ensure the cpp graphics are extracted
outputs.upToDateWhen { false }
def cmd = Shell.getShellCommandLine("tar xf ${tarFile}")
commandLine cmd
}
task getManuallyEditedSourceDependencies(type:Exec) {
description = 'extract cppGraphics manually edited source'
// this task must run after the generated sources are copied because manually edited files can
// overwrite generated ones.
dependsOn getGeneratedSource
def tarFile = configurations.manuallyEditedSourceDependencies.singleFile.path
inputs.file tarFile
workingDir 'src/main/jni/cppGraphics'
def cmd = Shell.getShellCommandLine("tar xf ${tarFile}")
commandLine cmd
}
task getAndroidNdkDir(type:Exec) {
}
getAndroidNdkDir.onlyIf {
!androidNdkInstalled()
}
task getAndroidNdk() {
}
task createSwigOutputDir {
doLast {
def swigOutputDir = file('src/main/java/com/tcs/app/graphics/gen')
FileExtension.mkdirs(swigOutputDir)
}
}
task getAndroidAvdDir(type:Exec) {
}
getAndroidAvdDir.onlyIf {
!androidAvdInstalled()
}
task getAndroidAvd() {
}
task swigBuild(type: Exec) {
dependsOn extractGraphics
dependsOn getGeneratedSource
dependsOn getManuallyEditedSourceDependencies
dependsOn createSwigOutputDir
dependsOn extractEigen
workingDir 'src/main/jni'
commandLine '/usr/local/bin/swig', '-java', '-c++', '-package', 'com.tcs.app.graphics.gen', '-outdir', '../java/com/tcs/app/graphics/gen', '-o', './graphics_wrap.cpp', 'graphics.i'
}
def numCompilationThreads = {
def (exitValue, numCompileThreads) = Shell.shellCommandReturningExitValueAndOutput("sysctl -n hw.ncpu");
if (exitValue != 0) {
return 1
}
return numCompileThreads
}
// call regular ndk-build(.cmd) script from app directory
// http://stackoverflow.com/questions/16667903/android-studio-gradle-and-ndk
// http://ph0b.com/android-studio-gradle-and-ndk-integration/
// TODO: We'd rather not have two tasks here. Either research whether we can just use the default NDK build with our own Android.mk, or figure out how to streamline this w/Gradle.
task ndkBuildDebug(type: Exec) {
}
task ndkBuildRelease(type: Exec) {
}
// TODO: do not brute force delete the graphics generated files. Instead, tell gradle they are output files, and
// let gradle automatically clean them
task cleanGraphicsGen(type: Delete) {
}
clean.dependsOn(cleanGraphicsGen)
// TODO: This is a more complete way to get the dependencies in place, but we need to figure out how to get the
// TODO: buildtype so we can refer to the correct ndkBuild task...
//tasks.withType(JavaCompile) {
// compileTask -> compileTask.dependsOn ndkBuild
//}
dependencies {
implementation 'androidx.core:core-ktx:1.3.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'com.google.android.material:material:1.1.0-alpha08'
implementation 'androidx.viewpager2:viewpager2:1.0.0-beta02'
implementation 'androidx.viewpager:viewpager:1.0.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation("com.tcs:tcs-android:$serializableLibVersion") {
transitive = false
}
implementation("com.tcs:tcs-primogenitor:$serializableLibVersion") {
transitive = false
}
implementation("com.tcs:tcs-serialize-common:$serializableLibVersion") {
transitive = false
}
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
implementation 'androidx.legacy:legacy-support-v13:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.percentlayout:percentlayout:1.0.0'
implementation 'com.google.android.gms:play-services-analytics:16.0.8'
implementation 'com.google.firebase:firebase-core:18.0.0'
implementation 'com.google.firebase:firebase-analytics:18.0.0'
implementation "com.google.firebase:firebase-messaging:17.5.0"
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.0.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.0"))
// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
implementation("com.google.guava:guava:31.0.1-android")
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.0'
implementation 'commons-lang:commons-lang:2.6'
implementation 'org.slf4j:slf4j-api:1.7.13'
implementation 'com.melnykov:floatingactionbutton:1.3.0'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'net.danlew:android.joda:2.9.9.4'
implementation 'io.github.inflationx:calligraphy3:3.1.1'
implementation 'io.github.inflationx:viewpump:2.0.3'
]
implementation 'com.google.firebase:firebase-crashlytics:17.2.2'
androidTestImplementation('androidx.test.espresso:espresso-core:3.1.1') {
exclude module: 'support-annotations'
}
androidTestImplementation('androidx.test.espresso:espresso-idling-resource:3.1.1') {
exclude module: 'support-annotations'
}
androidTestImplementation "com.squareup.spoon:spoon-client:2.0.0-SNAPSHOT" // For Spoon snapshot, until 2.0.0 is released
androidTestImplementation 'androidx.test:rules:1.1.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test:core:1.1.0'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-v4'
exclude group: 'com.android.support', module: 'design'
exclude group: 'com.android.support', module: 'recyclerview-v7'
}
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.constraintlayout:constraintlayout-solver:1.1.3'
androidTestImplementation 'junit:junit:4.13'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
}
spoon {
def envSerial = System.env['ANDROID_SERIAL'];
if (envSerial) {
devices = [envSerial];
}
if (project.hasProperty('spoonClassName')) {
className = project.spoonClassName
}
if (project.hasProperty('spoonMethodName')) {
methodName = project.spoonMethodName
}
debug = true
adbTimeout = 10*60
// className = 'com.tcs.integration.smoketests'
// methodName = 'testSteeringWheel'
}
I get this error when gradle syncs:
Cause 1: com.android.build.gradle.internal.crash.ExternalApiUsageException: java.lang.IllegalArgumentException: Cannot change attributes of dependency configuration ':app:debugCompile' after it has been resolved
Caused by: java.lang.IllegalArgumentException: Cannot change attributes of dependency configuration ':app:debugCompile' after it has been resolved
at org.gradle.api.internal.attributes.ImmutableAttributeContainerWithErrorMessage.attribute(ImmutableAttributeContainerWithErrorMessage.java:57)
Cause 2: org.gradle.api.UnknownDomainObjectException: KotlinJvmAndroidCompilation with name 'debug' not found
There is no relevant code at all ...but according to the error message:
KotlinJvmAndroidCompilation with name 'debug' not found
I'd suggest to define android.buildTypes.debug, so that it would be known:
android {
buildTypes {
debug {}
}
}
But the answer may eventually rather be, to add Crashlytics on class-path (root build.gradle):
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
I saw messages like these in the gradlew --debug output.
RuntimeException: Configuration 'eigen' was resolved during configuration time
I ignored them at first because they didn't seem related to the exception displayed on the console.
I created an empty andriod studio project (with the kotlin-andorid plugin) and verified that could "build" without error.
I then added parts of our app/build.gradle file into the new project until I encountered the ':app:debugCompileOnly' error.
The error occurred when I added the extractEigen task.
That reminded me of the configuration resolution error I saw in the debug output.
I fixed the configuration resolution error and that fixed the ':app:debugCompileOnly'error.
(Fixed by a colleague)
Related
I am trying to generate a signed bundle and I get the following error:
* What went wrong:
Execution failed for task ':app:packageReleaseBundle'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.PackageBundleTask$BundleToolWorkAction
> File 'root/res/anim/accelerate_decelerate_interpolator.xml' uses reserved file or directory name 'res'.
My build gradle is:
apply plugin: "com.android.application"
import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os
project.ext.react = [
enableHermes: true, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}
android {
configurations {
compile.exclude group: 'com.google.android'
compile.exclude group: 'root/res/anim/accelerate_decelerate_interpolator.xml'
}
packagingOptions {
exclude 'AndroidManifest.xml'
exclude 'resources.arsc'
exclude 'root/res/anim/accelerate_decelerate_interpolator.xml'
}
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.proaction_member_app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
if (isNewArchitectureEnabled()) {
// We configure the CMake build only if you decide to opt-in for the New Architecture.
externalNativeBuild {
cmake {
arguments "-DPROJECT_BUILD_DIR=$buildDir",
"-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
"-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
"-DNODE_MODULES_DIR=$rootDir/../node_modules",
"-DANDROID_STL=c++_shared"
}
}
if (!enableSeparateBuildPerCPUArchitecture) {
ndk {
abiFilters (*reactNativeArchitectures())
}
}
}
}
if (isNewArchitectureEnabled()) {
// We configure the NDK build only if you decide to opt-in for the New Architecture.
externalNativeBuild {
cmake {
path "$projectDir/src/main/jni/CMakeLists.txt"
}
}
def reactAndroidProjectDir = project(':ReactAndroid').projectDir
def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
into("$buildDir/react-ndk/exported")
}
afterEvaluate {
// If you wish to add a custom TurboModule or component locally,
// you should uncomment this line.
// preBuild.dependsOn("generateCodegenArtifactsFromSchema")
preDebugBuild.dependsOn(packageReactNdkDebugLibs)
preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
// Due to a bug inside AGP, we have to explicitly set a dependency
// between configureCMakeDebug* tasks and the preBuild tasks.
// This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
configureCMakeDebug.dependsOn(preDebugBuild)
reactNativeArchitectures().each { architecture ->
tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
dependsOn("preDebugBuild")
}
tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
dependsOn("preReleaseBuild")
}
}
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include (*reactNativeArchitectures())
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
storeFile file('proaction_member_app.keystore')
storePassword 'ProactionMemberApp'
keyAlias 'proaction_member_app'
keyPassword 'ProactionMemberApp'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
// Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
//noinspection GradleDynamicVersion
implementation("com.facebook.react:hermes-engine:+") { // From node_modules
exclude group:'com.facebook.fbjni'
}
} else {
implementation jscFlavor
}
implementation 'tech.bubbl:bubbl-sdk:1.6.17'
implementation 'tech.bubbl.sdk.android.googlelibs:youtube-player:1.0.3'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
implementation "com.google.android.gms:play-services-location:16.0.0"
implementation "com.google.android.gms:play-services-maps:16.0.0"
implementation "com.google.android.gms:play-services-places:16.0.0"
implementation "com.google.android.exoplayer:exoplayer-core:2.18.1"
implementation "com.google.android.exoplayer:exoplayer-dash:2.18.1"
implementation "com.google.android.exoplayer:exoplayer-hls:2.18.1"
implementation "com.google.android.exoplayer:exoplayer-ui:2.18.1"
implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:2.18.1"
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.7.0'
implementation "com.google.android.gms:play-services-location:16.0.0"
implementation "com.google.android.gms:play-services-maps:16.0.0"
implementation "com.google.android.gms:play-services-places:16.0.0"
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.lukekorth:mailable_log:0.1.6'
implementation 'com.dreizak:miniball:1.0.3'
implementation 'com.google.firebase:firebase-messaging:21.1.0'
implementation 'com.google.firebase:firebase-core:21.1.1'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'com.google.firebase:firebase-auth:21.1.0'
// implementation platform('com.google.firebase:firebase-bom:31.0.3')
}
if (isNewArchitectureEnabled()) {
// If new architecture is enabled, we let you build RN from source
// Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
// This will be applied to all the imported transtitive dependency.
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("com.facebook.react:react-native"))
.using(project(":ReactAndroid"))
.because("On New Architecture we're building React Native from source")
substitute(module("com.facebook.react:hermes-engine"))
.using(project(":ReactAndroid:hermes-engine"))
.because("On New Architecture we're building Hermes from source")
}
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.implementation
into 'libs'
}
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
def isNewArchitectureEnabled() {
// To opt-in for the New Architecture, you can either:
// - Set `newArchEnabled` to true inside the `gradle.properties` file
// - Invoke gradle with `-newArchEnabled=true`
// - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}
I have absolutely no idea what can be causing this...
I am not an 'app developer' so all my attempts to resolve this are very much educated guesses,
I have tried:
adding
compile.exclude group: 'com.google.android'
compile.exclude group: 'root/res/anim/accelerate_decelerate_interpolator.xml'
to the code
I have googled the issue and cannot find anything!
I have absolutely no idea what can be causing this...
I am not an 'app developer' so all my attempts to resolve this are very much educated guesses,
I have tried:
adding
compile.exclude group: 'com.google.android'
compile.exclude group: 'root/res/anim/accelerate_decelerate_interpolator.xml'
to the code
I have googled the issue and cannot find anything!
I'm using Android Studio to work with tomahawk-android project, so i cloned the project using git, directly into the Android Studio, where it fails to build, saying;
Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1).
Searched in the following locations:
https://jcenter.bintray.com/com/android/tools/build/aapt2-proto/0.3.1/aapt2-proto-0.3.1.jar
build.gradle:
apply plugin: "com.android.application"
android {
implementationSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig {
minSdkVersion 15
targetSdkVersion 22
renderscriptTargetApi 20
renderscriptSupportModeEnabled true
def name = readVersionName()
def parts = name.split("[\\._-]")
def code = parts[0] + parts[1]
code = String.format("%-5s", code.substring(0, Math.min(5, code.size()))).replace(' ', '0')
code = Integer.parseInt(code)
versionName name
versionCode code
println("Using version name: $name")
println("Using version code: $code")
}
lintOptions {
abortOnError false
}
dexOptions {
jumboMode true
javaMaxHeapSize "2g"
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/ASL2.0'
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
def fileName = outputFile.name.
replace(".apk", "-" + defaultConfig.versionName + ".apk")
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
signingConfigs {
release
}
buildTypes {
release {
zipAlignEnabled true
minifyEnabled true
proguardFiles "../proguard-android.txt"
}
debug {
versionNameSuffix "_debug"
zipAlignEnabled true
}
}
splits {
abi {
enable true
reset()
include 'armeabi-v7a', 'arm64-v8a', 'mips', 'x86', 'x86_64'
universalApk true
}
}
}
// map for the version code
ext.versionCodes = ['armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 4, 'x86': 6, 'x86_64': 7]
android.applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
output.versionCodeOverride =
project.ext.versionCodes.
get(output.getFilter(com.android.build.OutputFile.ABI), 9) * 100000 +
android.defaultConfig.versionCode
println("Using version name: $output.versionCodeOverride")
}
// assign different version name for each output
variant.outputs.each { output ->
def suffix = "_universal"
if (output.getFilter(com.android.build.OutputFile.ABI) != null) {
suffix = "_" + output.getFilter(com.android.build.OutputFile.ABI)
}
output.versionNameOverride = android.defaultConfig.versionName + suffix
}
}
def Properties props = new Properties()
def propFile = file('signing.properties')
if (propFile.canRead()) {
props.load(new FileInputStream(propFile))
if (props != null && props.containsKey('STORE_FILE') && props.containsKey('STORE_PASSWORD') &&
props.containsKey('KEY_ALIAS') && props.containsKey('KEY_PASSWORD')) {
android.signingConfigs.release.storeFile = file(props['STORE_FILE'])
android.signingConfigs.release.storePassword = props['STORE_PASSWORD']
android.signingConfigs.release.keyAlias = props['KEY_ALIAS']
android.signingConfigs.release.keyPassword = props['KEY_PASSWORD']
android.buildTypes.release.signingConfig = android.signingConfigs.release
android.buildTypes.debug.signingConfig = android.signingConfigs.release
}
}
buildscript {
repositories {
google() // here
jcenter()
}
dependencies {
implementation group: 'com.android.tools.build', name: 'aapt2-proto', version: '0.1.0'
classpath 'com.android.tools.build:gradle:3.2.0'
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation (name: 'circularprogressview-debug', ext: 'aar')
implementation 'com.android.support:appcompat-v7:24.1.1'
implementation 'com.android.support:support-v4:24.1.1'
implementation 'se.emilsjolander:stickylistheaders:2.7.0'
implementation('ch.acra:acra:4.7.0') {
transitive = false
}
implementation 'com.google.code.gson:gson:2.5'
implementation 'com.google.android.gms:play-services-base:8.4.0'
implementation('com.stanfy:gson-xml-java:0.1.7') {
exclude group: 'xmlpull', module: 'xmlpull'
}
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.squareup.okhttp:okhttp:2.7.2'
implementation 'com.squareup.okhttp:okhttp-urlconnection:2.7.2'
implementation 'com.squareup.okhttp:logging-interceptor:2.7.2'
implementation 'com.github.castorflex.smoothprogressbar:library:1.1.0'
implementation 'de.mrmaffen:vlc-android-sdk:1.9.8'
implementation 'org.apache.lucene:lucene-core:4.7.2'
implementation 'org.apache.lucene:lucene-analyzers-common:4.7.2'
implementation 'org.apache.lucene:lucene-queryparser:4.7.2'
implementation 'commons-io:commons-io:2.4'
implementation 'net.sourceforge.findbugs:jsr305:1.3.7'
implementation 'com.squareup.retrofit:retrofit:1.9.0'
implementation 'com.sothree.slidinguppanel:library:3.2.1'
implementation 'com.uservoice:uservoice-android-sdk:1.2.4'
implementation 'de.greenrobot:eventbus:2.4.1'
implementation 'com.daimajia.swipelayout:library:1.2.0#aar'
implementation 'org.jdeferred:jdeferred-android-aar:1.2.4'
implementation 'org.slf4j:slf4j-android:1.7.13'
}
}
allprojects {
repositories {
google() // and here
jcenter()
}
}
gradlew -v output:
------------------------------------------------------------
Gradle 4.6
------------------------------------------------------------
Build time: 2018-02-28 13:36:36 UTC
Revision: 8fa6ce7945b640e6168488e4417f9bb96e4ab46c
Groovy: 2.4.12
Ant: Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM: 1.8.0_172 (Oracle Corporation 25.172-b11)
OS: Windows 10 10.0 amd64
Thanks!!
This is due you didn’t put google() as the first repo. The order of google() matters. So just add it above jcenter() will solve your problem.
See https://stackoverflow.com/a/51151050/8034839
Note that this change should be in your TOP level build.gradle file. E.g.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google() // first one
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google() // first one
jcenter()
}
}
Note:
Since Android Gradle Plugin (AGP) version 3.0.0 (Gradle version 4.1+), Google introduced its own Google's Maven repository google(), most of the dependencies were moved to there. So, if you are using the AGP 3.0+, you should refer to this NEW repo firstly.
And here is some explanation about different gradle versions: What is real Android Studio Gradle Version?
Thanks for #HedeH, who linked me into his answer here, saying:
Try moving the google() method (In all .gradle files) to the top of
its execution block.
I did see that answer before while searching for the issue, but i missed that it must be changed "In all .gradle files".
Late answer,
delete the .gradle and .android directory after closing the Android Studio.
and open android studio again let it complete the sync and build.
After upgrading the Gradle plugin version to 3.0.0 (classpath "com.android.tools.build:gradle:3.0.0") and if I then try to clean or build the project I get this error:
A problem occurred configuring project ':app'.
> Manifest Tasks does not support the manifestOutputFile property any
more, please use the manifestOutputDirectory instead.
For more information, please check
https://developer.android.com/studio/build/gradle-plugin-3-0-0-
migration.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or
--debug option to get more log output.
* Get more help at https://help.gradle.org
I am not using manifestOutputFile anywhere in any of my gradle files. using the --debug and --stacktrace flags did nothing for me. I'm guessing this issue is coming up in one of my dependencies but I have no idea. Also, I am using Kotlin in a lot of classes; I'm not sure if that matters or not. Does anyone know if there is a way to see which library is throwing this error? Or does anyone have any suggestions or insight around this issue when the build.gradle file does not even reference manifestOutputFile?
Here's most of the build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
maven { url 'https://plugins.gradle.org/m2/' }
maven { url 'https://maven.google.com'}
}
dependencies {
classpath 'io.fabric.tools:gradle:1.24.4'
classpath 'me.tatarka:gradle-retrolambda:3.7.0'
classpath 'com.dicedmelon.gradle:jacoco-android:0.1.2'
classpath 'com.github.ben-manes:gradle-versions-plugin:0.17.0'
classpath 'gradle.plugin.com.nobleworks_software.icon-overlay:icon-overlay-plugin:1.2.3'
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'io.fabric'
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
apply plugin: 'jacoco'
apply plugin: 'jacoco-android'
apply plugin: 'com.github.ben-manes.versions'
apply plugin: 'com.nobleworks_software.icon-overlay'
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
flatDir {
dirs 'libs'
}
}
ext {
libsSrcDir = new File('${projectDir}/libs')
}
String gpsPropertyName = 'gps'
String gpsPropertyValueAlpha = 'alpha'
String gpsPropertyValueBeta = 'beta'
boolean tangoBuild = false
String tangoPropertyName = 'tango'
String alphaBuildEnding = '20'
String betaBuildEnding = '10'
String productionBuildEnding = '00'
def isBuildForGPS = { ->
return project.hasProperty(gpsPropertyName)
}
def isTangoBuild = { ->
return project.hasProperty(tangoPropertyName)
}
def getBranchName = { ->
try {
def branchOut = new ByteArrayOutputStream()
exec {
commandLine 'git', 'symbolic-ref', '--short', 'HEAD'
standardOutput = branchOut
}
return branchOut.toString().trim()
}
catch (ignored) {
return 'master'
}
}
def getVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--count', 'HEAD'
standardOutput = stdout
}
// Make the Tango version use '50' as the least sig offset
int tangoOffset = 0
if (tangoBuild) {
tangoOffset = 50
}
if (isBuildForGPS()) {
String channel = project.findProperty(gpsPropertyName)
if (gpsPropertyValueAlpha == channel) {
return Integer.parseInt(stdout.toString().trim() + alphaBuildEnding) + tangoOffset
} else if (gpsPropertyValueBeta == channel) {
return Integer.parseInt(stdout.toString().trim() + betaBuildEnding) + tangoOffset
}
}
return Integer.parseInt(stdout.toString().trim() + productionBuildEnding) + tangoOffset
}
catch (ignored) {
return -1
}
}
def getVersionName = { ->
try {
if (isBuildForGPS()) {
def tag = getLastTaggedVersion()
String channel = project.findProperty(gpsPropertyName)
if (gpsPropertyValueAlpha == channel) {
tag = tag + '-a'
} else if (gpsPropertyValueBeta == channel) {
tag = tag + '-b'
}
return tag
} else {
return getBranchName()
}
}
catch (ignored) {
return 'X.X.X'
}
}
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dexOptions {
javaMaxHeapSize "4g"
}
dataBinding {
enabled = true
}
defaultConfig {
versionCode getVersionCode()
versionName getVersionName()
applicationId getApplicationId()
minSdkVersion 16
targetSdkVersion 26
multiDexEnabled = true
multiDexKeepFile file('multidex_keep_file.txt')
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "com.demoapp.demoapp.WayTestRunner"
renderscriptTargetApi 16
renderscriptSupportModeEnabled true
String branchName = getBranchName().toUpperCase()
String iconOverlayText = branchName.toLowerCase()
buildConfigField "String", "LAST_TAGGED_VERSION", "\"${getLastTaggedVersion()}\""
if (branchName == 'DEV') {
iconOverlayText = 'ALPHA'
} else if (branchName.startsWith('RELEASE')) {
iconOverlayText = 'BETA'
}
if (!isBuildForGPS()) {
iconOverlay {
enabled = true
fontSize = 8
textColor = [255, 255, 255, 255]
verticalLinePadding = 2
backgroundOverlayColor = [0, 0, 0, 180]
text = { "$iconOverlayText" }
}
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
flavorDimensions("store", "3d_enabled")
productFlavors {
demoapp {
dimension = "store"
applicationId getApplicationId()
// Dupe required because SearchRecentSuggestionsProvider has no available context in its constructor
buildConfigField "String", "SEARCH_RECENT_AUTHORITY", "\"${applicationId}.WFSearchRecentSuggestionsProvider\""
// And one for the manifest
resValue "string", "SEARCH_RECENT_AUTHORITY", "${applicationId}.WFSearchRecentSuggestionsProvider"
// These need to be defined as string resources so they can be registered in the manifest.
// However in order to access them in tests it's convenient to have them also defined in BuildConfig
String deepLinkScheme = "demoappapp"
resValue "string", "EXPLICIT_DEEP_LINK_SCHEME1", deepLinkScheme
resValue "string", "EXPLICIT_DEEP_LINK_SCHEME2", deepLinkScheme
buildConfigField "String", "EXPLICIT_DEEP_LINK_SCHEME1", "\"${deepLinkScheme}\""
buildConfigField "String", "EXPLICIT_DEEP_LINK_SCHEME2", "\"${deepLinkScheme}\""
if (getBranchName().toUpperCase() == 'MASTER') {
manifestPlaceholders = [
appIcon : "#mipmap/ic_launcher",
appRoundIcon: "#mipmap/ic_launcher_round"
]
} else {
manifestPlaceholders = [
appIcon : "#mipmap/ic_launcher_dev",
appRoundIcon: "#mipmap/ic_launcher_dev_round"
]
}
}
demoappflavor {
dimension = "store"
applicationId getDemoappflavorApplicationId()
// Dupe required because SearchRecentSuggestionsProvider has no available context in its constructor
buildConfigField "String", "SEARCH_RECENT_AUTHORITY", "\"${applicationId}.WFSearchRecentSuggestionsProvider\""
// And one for the manifest
resValue "string", "SEARCH_RECENT_AUTHORITY", "${applicationId}.WFSearchRecentSuggestionsProvider"
// These need to be defined as string resources so they can be registered in the manifest.
// However in order to access them in tests it's convenient to have them also defined in BuildConfig
String deepLinkScheme1 = "theapp"
String deepLinkScheme2 = "demoappflavorapp"
resValue "string", "EXPLICIT_DEEP_LINK_SCHEME1", deepLinkScheme1
resValue "string", "EXPLICIT_DEEP_LINK_SCHEME2", deepLinkScheme2
buildConfigField "String", "EXPLICIT_DEEP_LINK_SCHEME1", "\"${deepLinkScheme1}\""
buildConfigField "String", "EXPLICIT_DEEP_LINK_SCHEME2", "\"${deepLinkScheme2}\""
manifestPlaceholders = [
appIcon : "#mipmap/ic_launcher",
appRoundIcon: "#mipmap/ic_launcher_round"
]
}
}
android.variantFilter { variant ->
def store = variant.getFlavors().get(0).name
def tango_enabled = variant.getFlavors().get(1).name
// Disable building the tango dimension
if ((store == 'demoappflavor' || !isTangoBuild()) && tango_enabled == "tangoEnabled") {
variant.setIgnore(true)
}
}
buildTypes {
release {
// Commented out to stop a production build crash with OKIO
//minifyEnabled true
// Commented out due to Gradle 2.2.0 issue
//shrinkResources true
ext.enableCrashlytics = true
apply plugin: 'signing'
signingConfig signingConfigs.release
ext.betaDistributionReleaseNotesFilePath = './release-notes.txt'
ext.betaDistributionGroupAliases = 'android-nightly'
buildConfigField 'boolean', 'OVERRIDE_MIN_VERSION', isBuildForGPS() ? 'false' : 'true'
buildConfigField 'boolean', 'ENABLE_APPSEE', isBuildForGPS() ? 'true' : 'false'
}
debug {
// TODO: Uncomment this out to enable code coverage
// testCoverageEnabled true
buildConfigField 'boolean', 'OVERRIDE_MIN_VERSION', isBuildForGPS() ? 'false' : 'true'
buildConfigField 'boolean', 'ENABLE_APPSEE', isBuildForGPS() ? 'true' : 'false'
}
configurations.all {
resolutionStrategy {
force 'com.google.code.findbugs:jsr305:1.3.9'
force 'com.google.guava:guava:21.0'
force "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
force 'com.google.code.gson:gson:2.8.2'
}
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
exclude 'bin/AndroidManifest.xml'
exclude 'bin/jarlist.cache'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
return 0
}
testOptions {
// Disable animations for UI testing
animationsDisabled = true
unitTests.returnDefaultValues = true
unitTests.all {
jacoco {
includeNoLocationClasses = true
}
}
}
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
}
configurations {
demoappTangoEnabledCompile
}
allprojects {
repositories {
jcenter()
maven { url 'https://jitpack.io' }
maven { url "https://clojars.org/repo/" }
}
}
ext.daggerVersion = '2.11'
ext.playServicesVersion = '11.6.2'
ext.supportLibsVersion = '27.0.1'
ext.robolectricVersion = '3.3.2'
ext.frescoVersion = '1.5.0'
ext.leakCanaryVersion = '1.5.4'
ext.roomVersion ='1.0.0'
ext.butterKnifeVersion ='8.7.0'
ext.espressoVersion ='3.0.1'
ext.gsonVersion ='2.8.2'
ext.mockitoVersion ='2.9.0'
ext.dexmakerVersion ='1.2'
ext.icepickVersion ='3.2.0'
ext.multidexVersion ='1.0.2'
dependencies {
// Compile Project
compile(project(':models'))
// Compile
compile('com.crashlytics.sdk.android:crashlytics:2.7.1#aar') {
transitive = true
}
// GOOGLE LIBS
compile "com.android.support:design:${supportLibsVersion}"
compile "com.android.support:recyclerview-v7:${supportLibsVersion}"
compile "com.android.support:cardview-v7:${supportLibsVersion}"
compile "com.android.support:support-v4:${supportLibsVersion}"
compile "com.android.support:support-v13:${supportLibsVersion}"
compile "com.android.support:percent:${supportLibsVersion}"
compile "com.android.support:support-annotations:${supportLibsVersion}"
compile "com.android.support:appcompat-v7:${supportLibsVersion}"
compile "com.android.support:multidex:${multidexVersion}"
compile "com.google.code.gson:gson:${gsonVersion}"
// FIREBASE AND PLAY SERVICES
compile "com.google.firebase:firebase-messaging:${playServicesVersion}"
compile "com.google.firebase:firebase-appindexing:${playServicesVersion}"
//noinspection GradleDependency
compile "com.google.android.gms:play-services-analytics:${playServicesVersion}"
//noinspection GradleDependency
compile "com.google.android.gms:play-services-auth:${playServicesVersion}"
//noinspection GradleDependency
compile "com.google.android.gms:play-services-wallet:${playServicesVersion}"
// FLOW LAYOUT FOR CHIPS
compile 'org.apmem.tools:layouts:1.10#aar'
// RxJava and related
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile project(':FloatingSearchView')
// RxJava support for Room
compile 'android.arch.persistence.room:rxjava2:1.0.0'
// Testing support
androidTestCompile 'android.arch.core:core-testing:1.1.0'
// Dagger
compile "com.google.dagger:dagger:${daggerVersion}"
compile "com.google.dagger:dagger-android-support:${daggerVersion}"
kapt "com.google.dagger:dagger-compiler:${daggerVersion}"
kapt "com.google.dagger:dagger-android-processor:${daggerVersion}"
compile ("com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}") {
exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
compile "com.jakewharton:butterknife:${butterKnifeVersion}"
kapt "com.jakewharton:butterknife-compiler:${butterKnifeVersion}"
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta4'
compile 'com.appsee:appsee-android:2.3.4'
compile 'commons-io:commons-io:2.5'
compile "com.android.support.test:runner:1.0.1"
// ESPRESSO
androidTestCompile "com.android.support:support-v4:${supportLibsVersion}"
androidTestCompile "com.android.support:support-annotations:${supportLibsVersion}"
androidTestCompile "com.android.support:recyclerview-v7:${supportLibsVersion}"
androidTestCompile "com.android.support:design:${supportLibsVersion}"
androidTestCompile "com.android.support:recyclerview-v7:${supportLibsVersion}"
androidTestCompile "com.android.support.test.espresso:espresso-core:${espressoVersion}"
androidTestCompile "com.android.support.test.espresso:espresso-intents:${espressoVersion}"
androidTestCompile "com.android.support.test.espresso:espresso-contrib:${espressoVersion}"
androidTestCompile "com.android.support.test.espresso:espresso-web:${espressoVersion}"
androidTestCompile "org.mockito:mockito-core:${mockitoVersion}"
androidTestCompile "com.google.dexmaker:dexmaker:${dexmakerVersion}"
androidTestCompile "com.google.dexmaker:dexmaker-mockito:${dexmakerVersion}"
androidTestCompile "com.android.support:multidex:${multidexVersion}"
androidTestCompile "org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}"
androidTestCompile "org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}"
androidTestCompile "com.google.code.gson:gson:${gsonVersion}"
androidTestCompile('com.jakewharton.espresso:okhttp3-idling-resource:1.0.0') {
//Using App Version Instead
exclude group: 'com.squareup.okio', module: 'okio'
exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
//WireMock
androidTestCompile( project(":wiremock")) {
//Using Android Version Instead
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
exclude group: 'org.ow2.asm', module: 'asm'
//Using Android Version Instead
exclude group: 'org.json', module: 'json'
exclude group: 'com.google.guava', module: 'guava'
}
androidTestCompile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:${mockitoVersion}"
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile "org.robolectric:robolectric:${robolectricVersion}"
testCompile "org.robolectric:shadows-multidex:${robolectricVersion}"
testCompile "org.robolectric:shadows-support-v4:${robolectricVersion}"
testCompile "com.google.code.gson:gson:${gsonVersion}"
testCompile "com.google.dagger:dagger:${daggerVersion}"
testCompile "com.android.support:multidex:${multidexVersion}"
kaptTest "com.google.dagger:dagger-compiler:${daggerVersion}"
// Kotlin mockito
testCompile ("com.nhaarman:mockito-kotlin-kt1.1:1.5.0"){
exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib'
exclude group: 'org.jetbrains.kotlin', module: 'kotlin-reflect'
}
compile "frankiesardo:icepick:${icepickVersion}"
provided "frankiesardo:icepick-processor:${icepickVersion}"
compile "com.facebook.fresco:fresco:${frescoVersion}"
compile "com.facebook.fresco:animated-gif:${frescoVersion}"
// Canary
debugCompile "com.squareup.leakcanary:leakcanary-android:${leakCanaryVersion}"
releaseCompile "com.squareup.leakcanary:leakcanary-android-no-op:${leakCanaryVersion}"
androidTestCompile "com.squareup.leakcanary:leakcanary-android-no-op:${leakCanaryVersion}"
testCompile "com.squareup.leakcanary:leakcanary-android-no-op:${leakCanaryVersion}"
compile 'com.prolificinteractive:material-calendarview:1.4.3'
//Card IO
compile 'io.card:android-sdk:5.5.1'
compile 'com.facebook.rebound:rebound:0.3.8'
//Chrome Web-View
compile "com.android.support:customtabs:${supportLibsVersion}"
def folder = new File('./brickkit-android/BrickKit/bricks/build.gradle')
if (folder.exists()) {
compile project(':bricks')
} else {
compile 'com.demoapp:brickkit-android:0.9.27'
}
// intellij annotations are included in kotlin, so this creates
// a "java.util.zip.ZipException: duplicate entry" on its modules
//compile 'com.intellij:annotations:12.0#jar'
testCompile "com.google.dagger:dagger:${daggerVersion}"
demoappTangoEnabledCompile project(':demoappView')
compile ('com.perimeterx.sdk:msdk:1.1.0') {
exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
// Kotlin support
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlinVersion"
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
//Data binding
kapt "com.android.databinding:compiler:$gradleVersion"
compile 'nl.littlerobots.rxlint:rxlint:1.4'
// Room
compile "android.arch.persistence.room:runtime:${roomVersion}"
kapt "android.arch.persistence.room:compiler:${roomVersion}"
androidTestCompile "android.arch.persistence.room:testing:${roomVersion}"
// Stetho
compile 'com.facebook.stetho:stetho:1.5.0'
compile 'com.facebook.stetho:stetho-js-rhino:1.4.2'
compile 'com.siftscience:sift-android:0.9.10'
}
import groovy.json.JsonBuilder
task uploadapithingFiles << {
// Get all the apithing files
String apithingDir = "${project.rootDir}/models/src/main/java/com/demoapp/models/requests/apithing-files"
FileTree files = fileTree(dir: apithingDir)
// TreeMap of File names and File Data
TreeMap<String, String> fileMap = new TreeMap<>()
files.each { file ->
Scanner input = new Scanner(file)
String output = ""
while (input.hasNext()) {
output = output + input.nextLine()
}
input.close()
fileMap.put(file.name.take(file.name.lastIndexOf('.')), output)
}
// Build request JSON
def json = new JsonBuilder()
json{
payload {
build_id getVersionCode()
client_id 2
version lastTaggedVersion
is_production isBuildForGPS() ? 1 : 0
queries fileMap.collect {
[
"name": it.key,
"query": it.value
]
}
}
}
// Create POST Request
def url = 'http://services.demoapp.com:8280/purest/performance/app_apithing'
def post = new URL(url).openConnection()
def message = json.toString()
projects.logger.debug(message)
post.setRequestMethod("POST")
post.setRequestProperty("Content-Type", "application/json; charset=utf-8")
post.setDoOutput(true)
post.getOutputStream().write(message.getBytes("UTF-8"))
def responseCode = post.getResponseCode()
if(responseCode >= 200 && responseCode <= 299) {
projects.logger.lifecycle("apithing upload successful.")
} else {
projects.logger.lifecycle("apithing Upload Failed with response: ${post.getResponseMessage()}")
throw new GradleException("ERROR: Unable to upload apithing files. Server returned a response code: ${responseCode}")
}
}
project.gradle.taskGraph.whenReady {
->
project.tasks.findAll { it.name =~ /connected.+AndroidTest/ }.each {
it.ignoreFailures = true
}
}
def errorOutput(dir) {
println "\n\n================OUTPUT REPORT=================\n\n"
println "The file $dir does not exist\n "
println "Check the current APK Path and Version "
println "\n\n==============================================\n\n"
}
def executeUpload(dir, isUpload, key) {
if (isUpload) {
exec {
commandLine 'curl', 'https://tok_gh6e7yrydkhgqyaz2fvx702y8m#api.appetize.io/v1/apps', '-F', "file=#$dir", '-F', 'platform=android'
}
} else {
exec {
commandLine 'curl', "https://tok_gh6e7yrydkhgqyaz2fvx702y8m#api.appetize.io/v1/apps/$key", '-F', "file=#$dir", '-F', 'platform=android'
}
}
}
apply plugin: 'com.google.gms.google-services'
jacocoAndroidUnitTestReport {
excludes += ['**/R.class','**/R$*.class','**/*$ViewInjector*.*','**/*$ViewBinder*.*','**/BuildConfig.*','**/Manifest*.*','**/*$Lambda$*.*','**/*Module.*','**/*Dagger*.*','**/*MembersInjector*.*','**/*_Provide*Factory*.*','**/*_Factory*.*','**/*$*$*.*','**/test*/**','**/androidTest/**','**/databinding/**']
}
tasks.whenTaskAdded { task ->
if (task.name == 'connecteddemoappDebugAndroidTest' || task.name == 'connecteddemoappflavorDebugAndroidTest') {
task.doFirst() {
exec {
commandLine 'sh', 'get_android_wiremock.sh'
}
}
task.doLast() {
exec {
commandLine 'sh', 'get_device_recordings.sh', 'wiremock_blacklist.txt'
}
}
}
}
android.applicationVariants.all { variant ->
task("checkstyle${variant.name.capitalize()}", type: Checkstyle) {
configFile file("${project.rootDir}/config/quality/checkstyle/checkstyle.xml")
configProperties.checkstyleSuppressionsPath = file("${project.rootDir}/config/quality/checkstyle/suppressions.xml").absolutePath
source 'src'
include '**/*.java'
exclude '**/gen/**'
exclude '**/models/generated/**'
classpath = files() as FileCollection
group = "verification"
}
check.dependsOn("checkstyle${variant.name.capitalize()}")
}
android.applicationVariants.all { variant ->
task("findbugs${variant.name.capitalize()}", type: FindBugs) {
ignoreFailures = false
effort = "default"
reportLevel = "medium"
excludeFilter = new File("${project.rootDir}/config/quality/findbugs/findbugs-filter.xml")
classes = files("${project.rootDir}/app/build/intermediates/classes")
source = fileTree('src/main/java/')
classpath = files()
group = "verification"
reports {
xml.enabled = false
html.enabled = true
xml {
destination "$project.buildDir/findbugs/findbugs-output.xml"
}
html {
destination "$project.buildDir/findbugs/findbugs-output.html"
}
}
dependsOn "compile${variant.name.capitalize()}JavaWithJavac"
}
check.dependsOn("findbugs${variant.name.capitalize()}")
}
android.applicationVariants.all { variant ->
task("buildCheckTest${variant.name.capitalize()}", type: GradleBuild) {
dependsOn "checkstyle${variant.name.capitalize()}"
dependsOn "assemble${variant.name.capitalize()}"
dependsOn "lint${variant.name.capitalize()}"
dependsOn "findbugs${variant.name.capitalize()}"
dependsOn "test${variant.name.capitalize()}UnitTest"
dependsOn "jacocoTest${variant.name.capitalize()}UnitTestReport"
mustRunAfter "clean"
}
}
task buildReleaseTest(type: GradleBuild)
android.applicationVariants.all { variant ->
if (variant.name.endsWith("Release")) {
buildReleaseTest.dependsOn("buildCheckTest${variant.name.capitalize()}")
}
}
android.applicationVariants.all { v ->
if (v.buildType.name == "release"){
v.assemble.dependsOn("uploadapithingFiles")
}
}
buildReleaseTest.mustRunAfter('clean')
task cleanBuildReleaseTest(type: GradleBuild)
cleanBuildReleaseTest.dependsOn('clean')
cleanBuildReleaseTest.dependsOn('buildReleaseTest')
Whoa, that's a lot of plugins. The error message comes because one of them depends on an API that was changed in 3.x (hence migration link). You'll need to update the corresponding plugin.
Based on gradle dependencies run at step 3 below, my guess is gradle.plugin.com.nobleworks_software.icon-overlay:icon-overlay-plugin. It shows com.android.tools.build:gradle:2.2.3 -> 3.0.1 nested under.
(gradlew buildEnvironment on your project may also give you a similar result if you add 3.0.1 Android Gradle Plugin to your build.gradle)
--stacktrace should have also given you the exact location where com.android.build.gradle.tasks.ManifestProcessorTask#getManifestOutputFile was called from. If it doesn't you can still do below:
This is a way I would answer this question if I had an mvce. You have too many plugins to set up everything manually from scratch. This method is also applicable to any Gradle buildscript weirdness in plugins.
Close your project in AS/IDEA
Note: if you have a buildSrc in your project that could also work, so there's no need to close and create another.
Create another project (let's call it debugger) with build.gradle file as follows:
buildscript {}'s contents from your project (but no buildscript block!)
repositories {
jcenter()
...
}
dependencies {
implementation ... // for each classpath ...
}
add plugins { id 'java' } on root level
add implementation 'com.android.tools.build:gradle:3.0.1' inside dependencies
Open this project in IDEA/Android Studio
(this will download all the sources for those plugins)
Run gradlew --no-daemon -Dorg.gradle.debug=true --debug --stacktrace from terminal
(this will stop executing and wait,
note: Listening for transport dt_socket at address: 5005)
Go to "Run/Debug configurations" dialog in debugger project
Create a "Remote" configuration (green +) with parameters from Gradle's log:
Close dialog with OK / Apply
Jump to class/file com.android.build.gradle.tasks.ManifestProcessorTask inside gradle-core-3.0.1-sources.jar
Put a breakpoint at line 128 in ManifestProcessorTask.getManifestOutputFile
To be safe repeat above two steps for gradle-core-3.0.1.jar's decompiled code as well. (line number may differ)
Run menu > Debug "Remote"
Wait and celebrate when breakpoint hits and you see who calls the method in the Debug view's Stack frame listing.
It looks overwhelming, but it's quite simple and fast after you did this once.
I am attempting to follow the Android Studio Experimental Plugin User Guide instructions located at:
http://tools.android.com/tech-docs/new-build-system/gradle-experimental
to modify the Mapbox GL Native library located at:
https://github.com/mapbox/mapbox-gl-native
In specific, I have modified the following Android files:
https://github.com/mapbox/mapbox-gl-native/blob/master/platform/android/gradle/wrapper/gradle-wrapper.properties
https://github.com/mapbox/mapbox-gl-native/blob/master/platform/android/build.gradle
https://github.com/mapbox/mapbox-gl-native/blob/master/platform/android/MapboxGLAndroidSDK/build.gradle
https://github.com/mapbox/mapbox-gl-native/blob/master/platform/android/MapboxGLAndroidSDKTestApp/build.gradle
My goal is to modify the library so I can debug it. Ideally I would be able to use Android Studio to build the library and debug the C/C++ code. So far I can build it, but I can't debug it. A programmer working at Mapbox told me they don't how to debug the Android code either, so I suspect this isn't an easy goal to reach.
I have made many different attempts to apply the Android Studio Experimental Plugin User Guide instructions, but I'm not experienced at Gradle and my latest attempt is leaving me with the following error message which I don't understand:
Gradle 'android' project refresh failed
Error:Cause:org.gradle.api.internal.ExtensibleDynamicObject
Does anyone know how to modify these files to have them build a debuggable Android NDK Library? What is causing the above error?
I am using:
> Linux Mint 17.2
> Android Studio 2.1.1
> Build #AI-143.2821654, built on April 28, 2016
> JRE: 1.8.0_65-b17 amd64
> JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation
Below are the 4 files as I currently have them modified. Since I am new to Gradle, do not assume I have made any modfications correctly. I was merely attempting to apply the Android Studio Experimental Plugin User Guide instructions until I got a successful build.
Thanks
#// mapbox-gl-native/platform/android/gradle/wrapper/gradle-wrapper.properties
#Thu Apr 07 14:21:05 CDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#//distributionUrl=https\://services.gradle.org/distributions/gradle-2.12-bin.zip
#//distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip
distributionSha256Sum=e77064981906cd0476ff1e0de3e6fef747bd18e140960f1915cca8ff6c33ab5c
// mapbox-gl-native/platform/android/MapboxGLAndroidSDKTestApp/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven { url 'https://jitpack.io' }
}
dependencies {
// classpath 'com.android.tools.build:gradle:2.1.0'
//classpath 'com.android.tools.build:gradle-experimental:0.7.0'
classpath 'com.android.tools.build:gradle-experimental:0.8.0-alpha2'
classpath 'com.github.JakeWharton:sdk-manager-plugin:220bf7a88a7072df3ed16dc8466fb144f2817070'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url "http://oss.sonatype.org/content/repositories/snapshots/" }
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.12'
}
// mapbox-gl-native/platform/android/MapboxGLAndroidSDK/build.gradle
apply plugin: 'android-sdk-manager'
apply plugin: 'com.android.model.library'
apply plugin: 'checkstyle'
apply plugin: 'maven'
apply plugin: 'signing'
allprojects {
group project.GROUP
version project.VERSION_NAME
repositories {
mavenCentral()
}
}
repositories {
mavenCentral()
}
ext {
supportLibVersion = '23.4.0'
}
dependencies {
compile "com.android.support:support-annotations:${supportLibVersion}"
compile "com.android.support:support-v4:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile 'com.squareup.okhttp3:okhttp:3.3.0'
compile 'com.mapzen.android:lost:1.1.0'
}
model {
android {
compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
minSdkVersion Integer.parseInt(project.ANDROID_MIN_SDK)
targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
}
sourceSets {
main.res.srcDirs += 'src/main/res-public'
}
repositories {
mavenCentral()
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
}
buildTypes {
debug {
jniDebuggable true
buildConfigField "String", "MAPBOX_EVENTS_USER_AGENT_BASE", new StringBuilder().append("\"").append("MapboxEventsAndroid/").append(project.VERSION_NAME).append("\"").toString()
}
release {
jniDebuggable false
buildConfigField "String", "MAPBOX_EVENTS_USER_AGENT_BASE", new StringBuilder().append("\"").append("MapboxEventsAndroid/").append(project.VERSION_NAME).append("\"").toString()
consumerProguardFiles 'proguard-rules.pro'
}
}
}
}
configurations {
all*.exclude group: 'commons-logging', module: 'commons-logging'
all*.exclude group: 'commons-collections', module: 'commons-collections'
}
model {
android.libraryVariants.all { variant ->
def name = variant.name
task "javadoc$name"(type: Javadoc) {
description = "Generates javadoc for build $name"
failOnError = false
destinationDir = new File(destinationDir, variant.baseName)
source = files(variant.javaCompile.source)
classpath = files(variant.javaCompile.classpath.files) + files(android.bootClasspath)
exclude '**/R.java', '**/BuildConfig.java', 'com/almeros/**'
options.windowTitle("Mapbox Android SDK $VERSION_NAME Reference")
options.docTitle("Mapbox Android SDK $VERSION_NAME")
options.header("Mapbox Android SDK $VERSION_NAME Reference")
options.bottom("© 2015–2016 Mapbox. All rights reserved.")
options.links("http://docs.oracle.com/javase/7/docs/api/")
options.linksOffline("http://d.android.com/reference/", "$System.env.ANDROID_HOME/docs/reference")
options.overview("src/main/java/overview.html")
options.group("Mapbox Android SDK", "com.mapbox.*")
options.group("Third Party Libraries", "com.almeros.*")
// TODO exclude generated R, BuildConfig, com.almeros.*
}
}
}
checkstyle {
configFile project.file('../checks.xml')
showViolations true
}
/*
task cleanJNIBuilds {
def jniLibsDir = new File("MapboxGLAndroidSDK/src/main/jniLibs")
delete jniLibsDir.absolutePath
}
*/
model
{
android.libraryVariants.all { variant ->
def name = variant.buildType.name
def checkstyle = project.tasks.create "checkstyle${name.capitalize()}", Checkstyle
checkstyle.dependsOn variant.javaCompile
checkstyle.source variant.javaCompile.source
checkstyle.classpath = project.fileTree(variant.javaCompile.destinationDir)
checkstyle.exclude('**/BuildConfig.java')
checkstyle.exclude('**/R.java')
checkstyle.exclude('**/com/almeros/android/multitouch/**')
project.tasks.getByName("check").dependsOn checkstyle
}
// From https://raw.github.com/mcxiaoke/gradle-mvn-push/master/jar.gradle
android.libraryVariants.all { variant ->
def jarTask = project.tasks.create(name: "jar${variant.name.capitalize()}", type: Jar) {
from variant.javaCompile.destinationDir
exclude "**/R.class"
exclude "**/BuildConfig.class"
}
jarTask.dependsOn variant.javaCompile
artifacts.add('archives', jarTask);
}
}
// From https://raw.github.com/mcxiaoke/gradle-mvn-push/master/gradle-mvn-push.gradle
def isReleaseBuild() {
return VERSION_NAME.contains("SNAPSHOT") == false
}
def getReleaseRepositoryUrl() {
return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL :
"https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}
def getSnapshotRepositoryUrl() {
return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL :
"https://oss.sonatype.org/content/repositories/snapshots/"
}
def getRepositoryUsername() {
return hasProperty('USERNAME') ? USERNAME :
(hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "")
}
def getRepositoryPassword() {
return hasProperty('PASSWORD') ? PASSWORD :
(hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "")
}
task apklib(type: Zip) {
appendix = extension = 'apklib'
from 'AndroidManifest.xml'
into('res') {
from 'res'
}
into('src') {
from 'src'
}
}
artifacts {
archives apklib
}
afterEvaluate { project ->
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
pom.groupId = GROUP
pom.artifactId = POM_ARTIFACT_ID
pom.version = VERSION_NAME
repository(url: getReleaseRepositoryUrl()) {
authentication(userName: getRepositoryUsername(),
password: getRepositoryPassword())
}
snapshotRepository(url: getSnapshotRepositoryUrl()) {
authentication(userName: getRepositoryUsername(),
password: getRepositoryPassword())
}
/*
// Leaving out as artifact was incorrectly named when found
addFilter('aar') { artifact, file ->
artifact.name == archivesBaseName
}
addFilter('apklib') { artifact, file ->
artifact.name == archivesBaseName + '-apklib'
}
*/
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
}
}
}
}
}
}
signing {
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
model {
task androidJavadocs(type: Javadoc) {
source = android.sourceSets.main.java.sourceFiles
classpath = files(android.bootClasspath)
}
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
model {
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.sourceFiles
}
}
artifacts {
archives androidSourcesJar
archives androidJavadocsJar
}
}
task makeClean(type: Exec) {
workingDir '../../'
commandLine 'make', 'clean'
}
task makeAndroid(type: Exec) {
workingDir '../../'
commandLine 'make', 'android'
}
task makeAndroidAll(type: Exec) {
workingDir '../../'
commandLine 'make', 'apackage'
}
// mapbox-gl-native/platform/android/MapboxGLAndroidSDKTestApp/build.gradle
apply plugin: 'android-sdk-manager'
apply plugin: 'com.android.model.application'
apply plugin: 'checkstyle'
task accessToken {
def tokenFile = new File("MapboxGLAndroidSDKTestApp/src/main/res/values/developer-config.xml")
if (!tokenFile.exists()) {
String tokenFileContents = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<resources>\n" +
" <string name=\"mapbox_access_token\">" + "$System.env.MAPBOX_ACCESS_TOKEN" + "</string>\n" +
"</resources>"
if (tokenFileContents == null) {
throw new InvalidUserDataException("You must set the MAPBOX_ACCESS_TOKEN environment variable.")
}
tokenFile.write(tokenFileContents)
}
}
gradle.projectsEvaluated {
// preBuild.dependsOn('accessToken')
}
ext {
supportLibVersion = '23.4.0'
}
model {
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.mapbox.mapboxsdk.testapp"
minSdkVersion.apiLevel 15
targetSdkVersion.apiLevel 23
versionCode 9
versionName "4.1.0"
// Specify AndroidJUnitRunner as the default test instrumentation runner
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'LICENSE.txt'
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'IconDensities'
disable 'InvalidPackage'
}
testOptions {
unitTests.returnDefaultValues = true
}
buildTypes {
debug {
// run code coverage reports
testCoverageEnabled = true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
}
dependencies {
compile(project(':MapboxGLAndroidSDK')) {
transitive = true
}
// Support libraries
compile "com.android.support:support-annotations:${supportLibVersion}"
compile "com.android.support:support-v4:${supportLibVersion}"
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:recyclerview-v7:${supportLibVersion}"
// Leak Canary
//debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta1'
//releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta1'
// Directions SDK
compile('com.mapbox.mapboxsdk:mapbox-android-directions:1.0.0#aar') {
transitive = true
}
// Geocoder SDK
compile('com.mapbox.mapboxsdk:mapbox-android-geocoder:1.0.0#aar') {
transitive = true
}
// Testing dependencies
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile "com.android.support:support-annotations:${supportLibVersion}"
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.5.4'
}
checkstyle {
configFile project.file('../checks.xml')
showViolations true
}
model {
android.applicationVariants.all { variant ->
def name = variant.buildType.name
def checkstyle = project.tasks.create "checkstyle${name.capitalize()}", Checkstyle
checkstyle.dependsOn variant.javaCompile
checkstyle.source variant.javaCompile.source
checkstyle.classpath = project.fileTree(variant.javaCompile.destinationDir)
checkstyle.exclude('**/BuildConfig.java')
checkstyle.exclude('**/R.java')
project.tasks.getByName("check").dependsOn checkstyle
}
}
Your gradle approach is essentially rewriting or porting the Android SDK Makefile to gradle. To solve what you are doing on Linux, you will likely need to modify the existing Makefiles.
The reason is that the Mapbox Android SDK build process uses make android to build the target libmapbox-gl.so. The Gradle project you have includes the .so file in with your usual Java code.
make android makes a call into mapbox-gl-native/Makefile
and also generates mapbox-gl-native/build/android-arm-v7/Makefile, which you may have to research how to modify to generate debug information as Chris Stratton mentions in the comments above.
When you do get around to modifying your C++, you will then need to modify the settings.gradle to make use of your modified .so for Android.
include ':MapboxGLAndroidSDK'
project(':MapboxGLAndroidSDK').projectDir = new File(rootProject.projectDir, '<relative-path-to>/../mapbox-gl-native/platform/android/MapboxGLAndroidSDK')
include ':app'
Another thing to consider — Can you build a debuggable version for Linux?
We have successfully debugged C++ for the Mapbox SDK using the Xcode debugger, as we built an iOS app as well. I know this will not fit your exact needs, but I mention it in case anyone else in your lab or organization has access to Xcode on OS X and can start debugging using make iproj.
I was using this template to incorporate robolectric tests but it's not working because I use flavors and I get this error:
Error:Could not find property 'testRelease' on project ':Component_Tests'.
How can I fix this? I'm using 2 flavors and 3 build types. Here's the gradle file:
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:0.12.1+'
classpath "com.neenbedankt.gradle.plugins:android-apt:1.2"
}
}
apply plugin: 'android'
apply plugin: 'android-apt'
apply from : "$rootDir/gradle/signing.gradle"
apply from : "$rootDir/gradle/build_extras.gradle"
apply from : "$rootDir/gradle/environments.gradle"
loadConfiguration()
apply from : "$rootDir/gradle/checkstyle.gradle"
apply from : "$rootDir/gradle/pmd.gradle"
apply from : "$rootDir/gradle/findbugs.gradle"
apply from : "$rootDir/gradle/espresso.gradle"
tasks.whenTaskAdded { task ->
if (task.name.startsWith('connectedAndroidTest')) {
task.dependsOn grantAnimationPermission
}
}
def loadPropertiesFile = { filePath ->
def propertiesFile = file(filePath)
def Properties properties = new Properties()
if (!propertiesFile.canRead()) {
throw new GradleException("cannot read " + filePath)
}
properties.load(new FileInputStream(propertiesFile))
return properties
}
def writePropertiesFile = { filePath, properties ->
def propertiesFile = file(filePath)
if (!propertiesFile.canRead()) {
throw new GradleException("cannot read " + filePath)
}
properties.store(propertiesFile.newWriter(), null)
}
def loadAndStorePropertyFile = { filePath, propertyName, value ->
def Properties properties = loadPropertiesFile(filePath)
properties[propertyName] = value.toString()
writePropertiesFile(filePath, properties)
println "$propertyName is set to $value"
}
def getVersionCode = { ->
def Properties versionProperties = loadPropertiesFile('../version.properties')
return versionProperties['VERSION_CODE'].toInteger()
}
def getAlphaHash = { ->
def Properties versionProperties = loadPropertiesFile('../version.properties')
return versionProperties['LAST_ALPHA_HASH'].toString()
}
def getBetaHash = { ->
def Properties versionProperties = loadPropertiesFile('../version.properties')
return versionProperties['LAST_BETA_HASH'].toString()
}
def getReleaseCandidateHash = { ->
def Properties versionProperties = loadPropertiesFile('../version.properties')
return versionProperties['LAST_RC_HASH'].toString()
}
def getCurrentHash = { ->
def cmd = "git rev-parse --short HEAD"
def gitProcess = cmd.execute()
def gitHash = gitProcess.text.trim()
return gitHash
}
def getReleaseNotes = { ->
def Properties versionProperties = loadPropertiesFile('../version.properties')
return versionProperties['NOTES'].toString()
}
def getReleaseNotesSinceHash = { hash ->
def cmd = "git log --pretty=-%x20[%h]%x20%s%n " + hash + "..HEAD"
def gitProcess = cmd.execute()
def notes = gitProcess.text.trim()
loadAndStorePropertyFile( '../version.properties', 'NOTES', notes)
}
def copyAndRenameZipAlignedPackage = { variant ->
def timeStamp = (int)(new Date().getTime() / 1000)
def versionCode = getVersionCode()
def gitHash = getCurrentHash()
def environment = project.environment
def file = variant.zipAlign.outputFile
def copyTask = project.tasks.create("copy${variant.name}Apk", Copy)
copyTask.from(file)
copyTask.into(file.parent)
if (variant.buildType.name == "release") {
copyTask.rename(".apk", "-" + environment + "-" + versionCode + "-"
+ gitHash + "-" + timeStamp + "-RELEASE.apk");
} else {
copyTask.rename(".apk", "-" + environment + "-" + versionCode + "-"
+ gitHash + "-" + timeStamp + "-SNAPSHOT.apk");
}
variant.assemble.dependsOn copyTask
copyTask.dependsOn variant.zipAlign
}
android {
compileSdkVersion 19
buildToolsVersion '19.1'
useOldManifestMerger true
defaultConfig {
applicationId 'com.example.app’
minSdkVersion 14
targetSdkVersion 19
versionCode getVersionCode()
testInstrumentationRunner 'com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner'
}
productFlavors {
dev {
// For explicit testing with Espresso and other frameworks.
}
hockey {
// For distro to stakeholders.
}
}
packagingOptions {
exclude 'LICENSE.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
}
lintOptions {
abortOnError true
}
jacoco {
version = '0.6.2.201302030002'
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
androidTest.setRoot('tests')
debug.setRoot('build-types/debug')
beta.setRoot('build-types/beta')
release.setRoot('build-types/release')
dev.setRoot('build-types/dev')
hockey.setRoot('build-types/hockey')
}
buildTypes {
debug {
applicationIdSuffix '.debug'
debuggable true
// still broken with dagger (espresso's dependency) as of 0.11.1
// https://code.google.com/p/android/issues/detail?id=69174
testCoverageEnabled false
}
beta {
applicationIdSuffix '.beta'
debuggable true
testCoverageEnabled false
signingConfig signingConfigs.betaSigning
}
release {
runProguard false
proguardFile 'proguard-config.txt'
signingConfig signingConfigs.releaseSigning
}
}
applicationVariants.all { variant ->
removeSetAnimationScaleFromManifest(variant)
task("generate${variant.name}Javadoc", type: Javadoc) {
description "Generates Javadoc for $variant.name."
group "Code Quality"
def Properties localProperties = loadPropertiesFile('../local.properties')
source = variant.javaCompile.source
classpath = files(variant.javaCompile.classpath.files) +
files(localProperties['sdk.dir'] + "/platforms/android-4.4.2/android.jar")
}
copyAndRenameZipAlignedPackage(variant)
}
}
apply plugin: 'monkey'
monkey {
teamCityLog = false
eventCount = 5000
seed = 42
failOnFailure = false
install = false
}
apply plugin: 'hockeyApp'
hockeyapp {
apiToken = “xxxxx”
releaseType = 0
notify = 0
status = 2
notesType = 1
commitSha = getCurrentHash()
notes = getReleaseNotes()
variantToApplicationId = [
hockeyDebug: “xxxxx”,
hockeyBeta: “xxxxx”,
hockeyRelease: “xxxxx”
]
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':android_ngn_stack:android-ngn-stack')
compile project(':SlidingMenuLibrary')
compile 'com.android.support:support-v4:19.1.+'
compile 'com.google.android.gms:play-services:5.0.77'
compile 'org.apache.james:apache-mime4j:0.6'
compile 'org.apache.httpcomponents:httpmime:4.2.3'
compile 'org.jsoup:jsoup:1.6.3'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.googlecode.ez-vcard:ez-vcard:0.9.3'
compile 'com.googlecode.libphonenumber:libphonenumber:5.9'
compile 'net.hockeyapp.android:HockeySDK:3.0.2'
compile("org.springframework.android:spring-android-auth:1.0.1.RELEASE") { exclude module: '*' }
compile("org.springframework.android:spring-android-core:1.0.1.RELEASE") { exclude module: '*' }
compile("org.springframework.android:spring-android-rest-template:1.0.1.RELEASE") { exclude module: '*' }
apt "org.androidannotations:androidannotations:" + androidAnnotationsVersion
provided 'com.jakewharton.espresso:espresso:1.1-r3'
androidTestCompile 'com.jakewharton.espresso:espresso:1.1-r3'
}
apt {
arguments {
androidManifestFile variant.processResources.manifestFile
resourcePackageName 'com.example’
}
Here's the test module gradle file:
buildscript {
dependencies {
classpath "com.android.tools.build:gradle:" + androidToolsBuildGradle
classpath "com.novoda:gradle-android-test-plugin:0.9.9-SNAPSHOT"
}
}
apply plugin: 'java'
test.reports.html.enabled = false // just clean up dashboard from not generated reports
test.reports.junitXml.enabled = false // just clean up dashboard from not generated reports
apply plugin: 'android-test'
apply plugin: "jacoco"
gradle.taskGraph.beforeTask { task ->
if (task.name == "compileTestJava") {
task.deleteAllActions()
println "Task $task.name is being rendered useless"
}
}
//Note - Alphabetical order matters for projectUnderTest
android {
projectUnderTest ':Acision_RCS_Client'
}
dependencies {
testCompile 'junit:junit:4.11'
testCompile 'org.mockito:mockito-core:1.9.5'
testCompile('com.squareup:fest-android:1.0.+') { exclude module: 'support-v4' }
testCompile('org.robolectric:robolectric:2.3') {
exclude module: 'classworlds'
exclude module: 'maven-artifact'
exclude module: 'maven-artifact-manager'
exclude module: 'maven-error-diagnostics'
exclude module: 'maven-model'
exclude module: 'maven-plugin-registry'
exclude module: 'maven-profile'
exclude module: 'maven-project'
exclude module: 'maven-settings'
exclude module: 'nekohtml'
exclude module: 'plexus-container-default'
exclude module: 'plexus-interpolation'
exclude module: 'plexus-utils'
exclude module: 'support-v4' // crazy but my android studio don't like this dependency and to fix it remove .idea and re import project
exclude module: 'wagon-file'
exclude module: 'wagon-http-lightweight'
exclude module: 'wagon-http-shared'
exclude module: 'wagon-provider-api'
}
}
apply from: "$rootDir/gradle/jacoco-support.gradle"
apply from: "$rootDir/gradle/android-studio-robolectric-support.gradle"
If you use product flavours, gradle will not find the "testRelease" task. You need to use the correct naming with the flavour, e.g. testFlavourRelease (Flavour must be replaced by a existing flavour name used in your project)