Android - 如何在gradle build中从bitbucket下载文本文件并将其添加到项目中

时间:2017-06-21 12:51:46

标签: android gradle android-gradle bitbucket

我在Bitbucket repo中有一些.txt文件(只有.txt文件不是android lib),我想通过Android studio(Gradle)在项目构建时添加到我的android项目中。

目标:随时修改远程文件内容,并在构建项目时添加更新的文件。

我经常研究但找不到任何解决方案。请帮忙。

1 个答案:

答案 0 :(得分:1)

您可以使用preBuild任务在构建之前下载文件,并使用this method执行下载。以下内容将文件下载到assets模块

app目录中
android {

    preBuild << {
        def url = "https://bitbucket.org/HellGate/jquery-slider/raw/5ab0c31aaa57fb7d321076194f462b472f5f031e/index.html"
        def file = new File('app/src/main/assets/index.html')
        new URL(url).withInputStream{ i -> file.withOutputStream{ it << i }}
    }
}

如果使用私有存储库,请使用基本身份验证方案username:password

android {

    preBuild << {
        def url = "https://username:password@bitbucket.org/HellGate/jquery-slider/raw/5ab0c31aaa57fb7d321076194f462b472f5f031e/index.html"
        def file = new File('app/src/main/assets/index.html')
        new URL(url).withInputStream{ i -> file.withOutputStream{ it << i }}
    }
}

在这种情况下,您可以将它们放在local.properties文件中(不提交凭据):

file_path=app/src/main/assets/index.html
ext_url=https://username:password@bitbucket.org/bertrandmartel/test/raw/c489ae46c3de9ad7089f53660a8de616af08265d/youtube.html

阅读preBuild任务中的属性:

preBuild << {

    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())

    if (properties.containsKey("file_path") && properties.containsKey("ext_url")) {
        def file = new File(properties.getProperty("file_path"))
        def url = properties.getProperty("ext_url")
        new URL(url).withInputStream{ i -> file.withOutputStream{ it << i }}
    }
    else{
        println("no properties found")
    }
}
相关问题