56

我正在构建一个 Android 应用程序,并希望维护一些环境变量,我可以根据我是处于开发模式还是发布模式来调整它们。例如,我需要调用一个 Web 服务,并且 URL 在任何一种模式下都会略有不同。我想将此设置和其他设置外部化,以便可以根据我的目标部署轻松更改它们。

SDK 中是否有任何最佳实践或任何内容来帮助满足此需求?

4

8 回答 8

44

以下解决方案假定您android:debuggable=true在开发和android:debuggable=false应用程序发布时始终在清单文件中设置。

ApplicationInfo.FLAG_DEBUGGABLE现在,您可以通过检查从中获取的标志来ApplicationInfo从代码中检查此属性的值PackageManager

以下代码片段可能会有所帮助:

PackageInfo packageInfo = ... // get package info for your context
int flags = packageInfo.applicationInfo.flags; 
if ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
    // development mode
} else {
    // release mode
}
于 2010-07-08T14:10:42.770 回答
32

根据这个 stackoverflow帖子,在 SDK Tools 版本 17(我们在撰写本文时为 19)添加了一个BuildConfig.DEBUG常量,该常量在构建开发版本时是正确的。

于 2012-05-19T04:31:32.177 回答
9

@viktor-bresan 感谢您提供有用的解决方案。如果您只包含一种检索当前应用程序上下文的通用方法以使其成为一个完整的工作示例,那将会更有帮助。类似于以下内容:

PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
于 2011-01-18T01:02:47.010 回答
8

Android build.gradle 很好地处理了调试和发布环境。

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
    }
于 2016-12-09T04:37:40.340 回答
4

我会检查isDebuggerConnected

于 2009-11-16T17:44:00.043 回答
3

像下面的代码怎么样......

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;

} 
于 2010-12-01T02:41:16.140 回答
1

我今天偶然发现了另一种方法,看起来非常简单。看看 Build.TAGS,当应用程序为开发而创建时,它的计算结果为字符串“test-keys”。

没有比字符串比较容易得多。

Build.MODEL 和 Build.PRODUCT 在模拟器上评估为字符串“google_sdk”!

于 2010-12-03T01:54:52.707 回答
0

这是我使用的方法:

http://whereblogger.klaki.net/2009/10/choosing-android-maps-api-key-at-run.html

我用它来切换调试日志和地图 API 密钥。

于 2010-08-25T16:23:12.407 回答