在Android上区分开发模式和发布模式环境设置
我正在构建一个Android应用程序,并希望维护一些环境变量,这些变量可以根据我处于开发模式还是发布模式进行调整。 例如,我需要调用一个Web服务,并且在任何一种模式下URL都会略有不同。 我想外部化此设置和其他设置,以便可以根据目标部署轻松更改它们。
SDK中是否有最佳实践或任何东西可以满足这一需求?
8个解决方案
44 votes
以下解决方案假定在开发过程中始终在清单文件中设置ApplicationInfo.FLAG_DEBUGGABLE,并为应用程序发布设置ApplicationInfo。
现在,您可以通过检查从PackageManager获得的ApplicationInfo中的ApplicationInfo.FLAG_DEBUGGABLE标志,从代码中检查此属性的值。
以下代码段可能会有所帮助:
PackageInfo packageInfo = ... // get package info for your context
int flags = packageInfo.applicationInfo.flags;
if ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// development mode
} else {
// release mode
}
Viktor Brešan answered 2019-12-24T19:35:10Z
29 votes
根据这篇stackoverflow的帖子,在SDK Tools版本17(我们撰写本文时为19)中添加了BuildConfig.DEBUG常量,该常量在构建开发版本时为true。
yincrash answered 2019-12-24T19:34:41Z
9 votes
@ viktor-bresan感谢您提供有用的解决方案。 如果您仅包括检索当前应用程序上下文的通用方法以使其成为一个可以正常工作的示例,那么它会有所帮助。 遵循以下内容:
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
Eron Villarreal answered 2019-12-24T19:35:30Z
6 votes
Android build.gradle具有良好的Handles Debug和Release Environment。
在build.gradle文件中附加以下代码段
buildTypes {
debug {
buildConfigField "Boolean", "IS_DEBUG_MODE", 'true'
}
release {
buildConfigField "Boolean", "IS_DEBUG_MODE", 'false'
}
}
现在您可以访问如下所示的变量
if (BuildConfig.IS_DEBUG_MODE) { {
//Debug mode.
} else {
//Release mode
}
Zumry Mohamed answered 2019-12-24T19:35:59Z
4 votes
我会检查isDebuggerConnected
Joseph answered 2019-12-24T19:36:19Z
3 votes
怎么样像下面的代码...
public void onCreate Bundle b ) {
super.onCreate(savedInstanceState);
if ( signedWithDebugKey(this,this.getClass()) ) {
blah blah blah
}
blah
blah
blah
}
static final String DEBUGKEY =
"get the debug key from logcat after calling the function below once from the emulator";
public static boolean signedWithDebugKey(Context context, Class> cls)
{
boolean result = false;
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(comp.getPackageName(),PackageManager.GET_SIGNATURES);
Signature sigs[] = pinfo.signatures;
for ( int i = 0; i < sigs.length;i++)
Log.d(TAG,sigs[i].toCharsString());
if (DEBUGKEY.equals(sigs[0].toCharsString())) {
result = true;
Log.d(TAG,"package has been signed with the debug key");
} else {
Log.d(TAG,"package signed with a key other than the debug key");
}
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return false;
}
return result;
}
Jeff S answered 2019-12-24T19:36:38Z
1 votes
今天,我偶然遇到了另一种似乎很简单的方法。看一下Build.TAGS,在为开发而创建应用程序时,它的评估结果为字符串“ test-keys”。
没有比字符串比较容易的多了。
Build.MODEL和Build.PRODUCT也会在模拟器上计算为字符串“ google_sdk”!
Jeff S answered 2019-12-24T19:37:07Z
0 votes
这是我使用的方法:
[http://whereblogger.klaki.net/2009/10/choosing-android-maps-api-key-at-run.html]
我用它来切换调试日志记录和maps API密钥。
wirbly answered 2019-12-24T19:37:36Z