简体   繁体   中英

Conditional build of dependant NDK with gradle

My project depends on a NDK. But my NDK build is different for my projectFlavors.

I like to build and pack my dependent NDK with -DFLAVOR1 compile option defined if app's flavor1 is selected for my app. -DFLAVOR2 when flavor2 is selected and etc.

My whole app will not work correctly if app is on flavor1 and incorrectly use a NDK built on -DFLAVOR2 , so the correct selection is important.

Now how we can write our build.gradle to solve this special conditional build?

I finally found a hacky approach for my problem, then I though it is better to share it here for everyone and improvement.

Step 1:

You need to provide flag from app and depend it on preBuild . Here is a sample code for doing it.Thanks How to get current flavor in gradle for function. I just modified it a little.

import java.util.regex.Matcher
import java.util.regex.Pattern

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern;

    if( tskReqStr.contains( ":app:assemble" ) )
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else if( tskReqStr.contains( ":app:generate" ) )
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("incremental(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher( tskReqStr )

    if( matcher.find() )
        return matcher.group(1).toLowerCase()
    else
    {
        println "NO MATCH FOUND"
        return "";
    }
}

task setFlavorFlag() {
    def flavorName = getCurrentFlavor();
    if (!flavorName.equals("")) {
        printf("Setting flag from app...\n")
        def f = file("../build/conf.tmp")
        if (!f.exists()) f.createNewFile()
        f.write("-D${flavorName.toUpperCase()}")
    }
}

preBuild.dependsOn setFlavorFlag

dependencies {
    compile project(path: ':mylibrary')
}

Step 2:

Access flag from library. I did it in ndk section:

ndk {
    ...
    def f = file("../build/conf.tmp")
    if (f.exists()) {
        printf("Building library for Flavor:%s\n", f.text)
        ndk.CFlags.add(f.text);
        f.delete()
    }
}

ok. Now your app Flavor is passed with a -D option to compile of library. Here was the approach I found after 2-3 days. I'm open for all improvements for this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM