Configure Gradle to execute custom build step before starting compilation - android

I've started using Gradle today and after searching for an hour and trying every possible answer from SO (e.g. 1) and different blogs (e.g. 2) and documentations (e.g. 3) I need some help.
My question is simple: How to execute a custom build-step (in my case the execution of ndk-build with a customized Android.mk) as part of the regular build-process?
The build.gradle looks like this:
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "myApp.prototype"
minSdkVersion 16
targetSdkVersion 19
testApplicationId "myApp.prototype.test"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
}
sourceSets.main.jni.srcDirs = []
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
def rootDir = project.rootDir
def localProperties = new File(rootDir, "local.properties")
Properties properties = new Properties()
localProperties.withInputStream { instr ->
properties.load(instr)
}
def ndkDir = properties.getProperty('ndk.dir')
println ndkDir
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine "$ndkDir\\ndk-build.cmd",
'NDK_PROJECT_PATH=build/intermediates/ndk',
'NDK_LIBS_OUT=src/main/jniLibs',
'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
'NDK_APPLICATION_MK=src/main/jni/Application.mk'
} else {
commandLine "$ndkDir/ndk-build",
'NDK_PROJECT_PATH=build/intermediates/ndk',
'NDK_LIBS_OUT=src/main/jniLibs',
'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:20.+'
compile 'com.google.android.gms:play-services-location:6.5+'
compile 'com.android.support:support-v4:19.1.0'
compile 'com.google.code.gson:gson:2.2.4'
compile fileTree(dir: new File(buildDir, 'libs'), include: '*.jar')
}
When executing gradle ndkBuild from the command-line, everything works fine. But I want that Android Studio automatically runs ndkBuild when it runs the rest of the Android compile procedures (such as generateDebugSources, preBuild, preDebugBuild, ...).
I have tried to attach myself to these events like this:
gradle.projectsEvaluated {
preBuild.dependsOn(ndkBuild)
}
but regardless where I put that code, or what task I use from the variety of tasks available (when running gradle tasks), nothing seems to work.

Have you tried adding a dependency for ndkBuild on JavaCompile tasks ?
android {
...
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}

Related

add-application.mk file not found in ndk-build android

I am using this https://github.com/quiet/org.quietmodem.Quiet link to transfer sound. This is a library so added it in project and in buld.gradle , i have compiled the project as :
compile project(':quiet')
My code for build.gradle(Module : quiet) is
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
debuggable = true
jniDebuggable = true
}
}
sourceSets { main {
jniLibs.srcDir 'src/main/libs'
jni.srcDirs = []
} }
externalNativeBuild{
ndkBuild{
path "$projectDir/src/main/jni/Android.mk"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support:support-annotations:23.0.0'
androidTestCompile 'com.android.support.test:rules:0.5'
androidTestCompile 'com.android.support.test:runner:0.5'
compile 'com.android.support:appcompat-v7:23.1.1'
}
def getNdkDir() {
if (System.env.ANDROID_NDK_ROOT != null)
return System.env.ANDROID_NDK_ROOT
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkdir = properties.getProperty('ndk.dir', null)
if (ndkdir == null)
throw new GradleException("NDK location not found. Define location with ndk.dir in the local.properties file or with an ANDROID_NDK_ROOT environment variable.")
return ndkdir
}
def getNdkBuildCmd() {
def ndkbuild = getNdkDir() + "/ndk-build"
if (Os.isFamily(Os.FAMILY_WINDOWS))
ndkbuild += ".cmd"
return ndkbuild
}
task ndkBuild(type:Exec, description: "Compile JNI Sources") {
workingDir file('src/main')
commandLine getNdkBuildCmd()
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkLibsToJar
}
task ndkLibsToJar(type: Zip, dependsOn: 'ndkBuild', description: 'Create a JAR of the native libs') {
destinationDir new File(buildDir, 'libs')
baseName 'ndk-libs'
extension 'jar'
from(new File(buildDir, 'libs')) { include '**/*.so' }
into 'lib/'
}
Now when i build my project , it throws ndk issues which is shown in the image
The issue I am facing is shown in the image

NDKBuild Failure in android studio

I'm having trouble getting my NDK to compile properly in Android Studio. Whenever I try running to compile I am getting the following error.
Error:Execution failed for task ':app:ndkBuild'. A problem occurred starting process 'command 'ndk-build.cmd''
build.gradle:-
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
defaultConfig {
applicationId "com.google.android.apps.watchme"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
sourceSets.main{
jniLibs.srcDir 'src/main/libs'
jni.srcDirs = [] //disable automatic ndk-build call
}
project.ext.versionCodes = ['armeabi':1, 'armeabi-v7a':2, 'arm64-v8a':3, 'mips':5, 'mips64':6, 'x86':8, 'x86_64':9] //versionCode digit for each supported ABI, with 64bit>32bit and x86>armeabi-*
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), 0) * 1000000 + defaultConfig.versionCode
}
}
// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine 'C:\\Users\\RAM-RAMADEVI\\AppData\\Local\\Android\\sdk\\ndk-bundle', '-C', file('src/main').absolutePath
} else {
commandLine 'ndk-build', '-C', file('src/main').absolutePath
}
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services-plus:7.8.0'
compile 'com.android.support:support-v4:23.0.0'
compile 'com.android.support:design:23.0.0'
compile 'com.google.apis:google-api-services-youtube:v3-rev120-1.19.0'
compile 'com.google.http-client:google-http-client-android:+'
compile 'com.google.api-client:google-api-client-android:+'
compile 'com.google.api-client:google-api-client-gson:+'
compile 'com.mcxiaoke.volley:library:1.0.18'
compile 'com.google.code.gson:gson:2.3'
}
local.properties:-
ndk.dir=C\:\\Users\\RAM-RAMADEVI\\AppData\\Local\\Android\\Sdk\\ndk-bundle
sdk.dir=C\:\\Users\\RAM-RAMADEVI\\AppData\\Local\\Android\\Sd
k

Cannot resolve symbol 'tools' and 'GradleException'

I have started to work on an existing project including Android NDK. I have two issues in build.gradle, which is impossible for me to build the app. For your information, my co-worker (who was working on it) was able to build the app.
I have already imported the NDK, from the project structures I can see the correct Android NDK path.
Here is how build.gradle looks like :
import org.apache.tools.ant.taskdefs.condition.Os
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
// The Fabric Gradle plugin uses an open ended version to react
// quickly to Android tooling updates
classpath 'io.fabric.tools:gradle:1.21.5'
}
}
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'realm-android'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
dataBinding{
enabled = true;
}
defaultConfig {
applicationId "com.lucien.myapp"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0.0"
ndk {
moduleName "DSPLib-jni"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets.main.jni.srcDirs = [] // disable automatic ndk-build call, which ignore our Android.mk
sourceSets.main.jniLibs.srcDir 'src/main/libs'
// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
workingDir file('src/main')
commandLine getNdkBuildCmd()
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task cleanNative(type: Exec) {
workingDir file('src/main')
commandLine getNdkBuildCmd(), 'clean'
}
clean.dependsOn cleanNative
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
compile 'com.android.support:support-v4:24.2.0'
compile 'com.github.PhilJay:MPAndroidChart:v2.2.5'
compile 'com.orhanobut:dialogplus:1.11#aar'
compile('com.crashlytics.sdk.android:crashlytics:2.6.2#aar') {
transitive = true;
}
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.google.code.gson:gson:2.7'
}
def getNdkDir() {
if (System.env.ANDROID_NDK_ROOT != null)
return System.env.ANDROID_NDK_ROOT
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkdir = properties.getProperty('ndk.dir', null)
if (ndkdir == null)
throw new GradleException("NDK location not found. Define location with ndk.dir in the local.properties file or with an ANDROID_NDK_ROOT environment variable.")
return ndkdir
}
def getNdkBuildCmd() {
def ndkbuild = getNdkDir() + "/ndk-build"
if (Os.isFamily(Os.FAMILY_WINDOWS))
ndkbuild += ".cmd"
return ndkbuild
}
I have an issue with the first line, trying to import "org.apache.tools.ant.taskdefs.condition.Os" : Cannot resolve symbol 'tools'
And the same kind of issue for "throw new GradleException("...")"
Do I need to update something in my build.gradle ? Or the issue is somewhere else ?
Thanks !
You can use any other available exceptions from java like:
throw new FileNotFoundException("Could not read version.properties!")
very simple delete new from build.gradle
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
delete new
throw GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
For those who come here, I resolved my issue by going back to Android Studio 2.1. Since the release of stable version 2.2, it's working great.
You can use
throw new FileNotFoundException("Flutter SDK not found")

Android NDK- Error:Execution failed for task ':app:buildNative'

I am developing an Video Compression app so i am using NDK and getting error when run the app.
I seen the many stackOverflow Questions (Execution error in app:buildNative) but the stackOverflow solutions are not works for this error.
Gradle Build Message:
Gradle tasks [:app:assembleDebug]
:app:buildNative FAILED
Error:Execution failed for task ':app:buildNative'.
> A problem occurred starting process 'command 'null/ndk-build.cmd''
Is anyone help for my questions?
build.gradle(Module:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "com.xxxx.videocompressor"
minSdkVersion 16
targetSdkVersion 22
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
sourceSets.main {
jni.srcDirs = [] // This prevents the auto generation of Android.mk
jniLibs.srcDir 'src/main/libs'
// This is not necessary unless you have precompiled libraries in your project.
}
task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build.cmd",
'-C', file('src/main/jni/').absolutePath, // Change src/main/jni the relative path to your jni source
'-j', Runtime.runtime.availableProcessors(),
'all',
'NDK_DEBUG=1'
}
task cleanNative(type: Exec, description: 'Clean JNI object files') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build.cmd",
'-C', file('src/main/jni/').absolutePath, // Change src/main/jni the relative path to your jni source
'clean'
}
clean.dependsOn 'cleanNative'
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildNative
}
productFlavors {
}
}
dependencies {
compile 'com.android.support:support-v4:22.2.+'
compile 'com.android.support:support-v4:22.2.+'
compile 'com.android.support:appcompat-v7:22.2.+'
compile 'com.android.support:recyclerview-v7:22.2.+'
compile 'com.android.support:design:22.2.+'
compile 'com.google.android.gms:play-services-ads:7.8.0'
}
Instead of using only this
// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
} else {
commandLine 'ndk-build', '-C', file('src/main').absolutePath
}
}
Use this
// call regular ndk-build(.cmd) script from app directory
task ndkBuild(type: Exec) {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
} else {
commandLine 'ndk-build', '-C', file('src/main').absolutePath
}
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}

Converting native Android app to gradle-experimental 0.2.0

I'm trying to convert any project tango sample app to use the new experimental gradle build system. I downloaded an app, verified that it builds and deploys, and then updated files following the experimental-gradle guide. The process was straight-forward, except for the app build.gradle file, shown below before and after my edits. I have been studying the gradle plugin, the experimental guide, etc, but haven't figured out what to do with sourceSets and the two tasks and keep getting errors. What is the right way to modify build.gradle?
Note:
I used point-cloud-jni-example, but these changes should be the same for any project tango app, because the relevant files are essentially identical for all the tango sample apps.
stock app build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.projecttango.experiments.nativepointcloud"
minSdkVersion 19
targetSdkVersion 19
}
sourceSets.main {
jniLibs.srcDir 'src/main/libs'
jni.srcDirs = [];
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task ndkBuild(type: Exec) {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkbuild = properties.getProperty('ndk.dir', null)+"/ndk-build"
commandLine ndkbuild, '-C', file('src/main/jni').absolutePath
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
modified app build.gradle:
apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 19
buildToolsVersion = "23.0.0"
defaultConfig.with {
applicationId = "com.projecttango.experiments.nativepointcloud"
minSdkVersion.apiLevel = 19
targetSdkVersion.apiLevel = 19
}
android.sourceSets.main {
jniLibs.srcDir = 'src/main/libs'
jni.srcDirs = [];
}
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
ndk.with {
debuggable = true
}
}
}
android.ndk {
moduleName = "point_cloud_jni_example"
ldLibs += ["android", "EGL", "GLESv2", "dl", "log"]
stl = "stlport_static"
}
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task ndkBuild(type: Exec) {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkbuild = properties.getProperty('ndk.dir', null)+"/ndk-build.cmd"
commandLine ndkbuild, '-C', file('src/main/jni').absolutePath
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
I am not sure if it resolves all issues.
In any case, you have to change your buildTypes block using:
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
}
}
Also use the last version 0.2.1

Categories

Resources