简体   繁体   English

如何让Android Gradle构建写入调试APK的文件

[英]How to have Android Gradle build write a file that goes into the debug APK

GenyMotion's localhost IP address (10.0.3.2) is different from the Android emulator's localhost IP (10.0.2.2). GenyMotion的localhost IP地址(10.0.3.2)与Android模拟器的localhost IP(10.0.2.2)不同。 Currently I have this in one of my source files: 目前,我的源文件之一中有此文件:

//val LOCALHOST = "10.0.2.2"  // Android emulator
val LOCALHOST = "10.0.3.2"  // Genymotion

and whenever I switch between a Linux box and a Mac box and fetch the latest sources, I have to uncomment one and comment the other before rebuilding. 每当我在Linux机器和Mac机器之间切换并获取最新的资源时,在重建之前,我都必须取消注释并评论另一种。

Unless someone can think of a better solution, I would like to have a Gradle task that writes out one of these values depending on the host OS, into a file that's included in the APK in such a way that I can access it from my Android app's runtime, and have that task run before assembleDebug when I build in Android Studio. 除非有人能想到更好的解决方案,否则我想拥有一个Gradle任务,该任务根据主机操作系统将其中一个值写出到APK包含的文件中,这样我就可以从Android上访问它了应用的运行时,并在我在Android Studio中构建时在assembleDebug调试之前运行该任务。

I suppose putting it in a resource would be easiest to access on the runtime side, but even a plain text file accessible to Class.getResourceAsStream() would be fine too. 我想将其放在资源中在运行时最容易访问,但是即使Class.getResourceAsStream()可访问的纯文本文件也可以。

I don't mind if it's included in the release apk, but I'd prefer that it just go into the debug ones. 我不介意它是否包含在发行版apk中,但我希望它只包含在调试版本中。

I would also prefer that the file be generated in my build/ output directory, so that it's invisible to version control. 我还希望该文件在我的build/输出目录中生成,这样它对于版本控制是不可见的。

Any idea how to go about this? 任何想法如何去做?

There are much better solutions like finding the local IP address using getNetworkInterfaces() , but as you asked how to pass some information from gradle, 有更好的解决方案,例如使用getNetworkInterfaces()查找本地IP地址,但是当您询问如何从gradle传递一些信息时,

android {
    productFlavors {
        flavorGenymotion {
            buildConfigField "String", "LOCALHOST", '"10.0.3.2"'
        }
        flavorEmulator {
            buildConfigField "String", "LOCALHOST", '"10.0.2.2"'
        }
    }
    ...

which you can access as BuildConfig.LOCALHOST . 您可以作为BuildConfig.LOCALHOST进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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