如何在 Android Studio 的运行/调试配置中将参数传递给 Java 代码 [英] How to pass a parameter to the Java code in run/debug configuration from Android Studio
问题描述
我的 android 应用程序向我的服务器发出一些 http 请求.但是,有时我正在调试在我的开发机器上运行的新 api 代码.我希望能够传递一些东西(比如一个环境变量),所以在我的代码中,如果它存在,我将能够使用它作为来自 android 模拟器的 api 请求的主机名.
My android app does some http requests to my server. However sometimes I am debugging the new api code that runs on my development machine. I would like to be able to pass something (like an environment variable) so in my code, if it's present I would be able to use that as the hostname for the api requests from the android emulator.
所以我正在寻找一种方法来传递类似的东西:
So I'm looking for a way to pass something like:
API_SERVER=http://10.0.2.2/myapp/
在我的代码中我会以某种方式使用它,例如:
and in my code I would use it somehow, for example:
final static String API_SERVER_REAL = "http://example.com/";
final String apiServerOverride = System.getenv("API_SERVER");
final String API_SERVER = (null != apiServerOverride && !apiServerOverride.isEmpty() ? apiServerOverride : API_SERVER_REAL);
推荐答案
我建议使用 productFlavors.每种风格都可以包含特定于环境的设置.我只是有一个名为Environment"的类,它包含我需要的所有 public static final String
并且每个产品风格都包含此类的不同版本,并为环境设置了值.
I suggest using productFlavors. Each flavor can contain environment specific settings. I simply have a class called 'Environment' which contains all the public static final String
s that I need and each product flavor includes an different version of this class with the values set for the environment.
这篇关于如何在 Android Studio 的运行/调试配置中将参数传递给 Java 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!