Eclipse Java:根据构建配置定义最终变量

时间:2012-09-06 09:15:26

标签: java android eclipse debugging build-process

我希望在运行项目的Debug版本时有一个final变量true,而在运行Run版本时我想false try { String line = null; java.lang.Process p = Runtime.getRuntime().exec("getprop debugging"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { Log.d("Property:", line); //<-- Parse data here. } input.close(); } catch (IOException e) { e.printStackTrace(); } 。我知道我可以通过构建配置来做到这一点但不知道如何在Eclipse中进行设置。在Stack Exchange上似乎没有关于具体定义变量的任何教程或问题。

我正在Eclipse Classic 4.2中编译Java,使用ADT插件创建一个Android应用程序。


编辑:根据@Xavi,我设置了以下内容:

-prop debugging=true

在Debug Configurations窗口的Target选项卡的“Additional Emulator Command Line Options”字段中,我输入了:

{{1}}

不幸的是,它看起来只适用于模拟器模式。在手机上运行时,它不会打印任何内容。 (它在模拟器上运行良好。)


编辑:Per @Sharks我发现一些看似相关的链接,但我不知道如何将它们应用到我的情况中:

3 个答案:

答案 0 :(得分:4)

如果您使用ADT在Eclipse中工作,那么您可以检查变量BuildConfig.DEBUG。它会自动生成并放在gen/<package>/BuildConfig.java

if (BuildConfig.DEBUG) {
   variable = true;
}

答案 1 :(得分:1)

除了@Yury的回答,您可以在其他仿真器命令行选项中使用-prop debugging=true,并在运行时通过Runtime.getRuntime().exec("getprop debugging")

进行检查

Screenshot of debug configuration

此外,您可能会发现以下问题很有用:Android: Release and testing mode?

答案 2 :(得分:0)

好的,因为命令行参数不适合你; Eclipse的那些不适合你,所以为什么不尝试这样的东西

  • 将配置文件放入APK的资产中。
  • 在变量赋值之前在静态块中读取文件
  • 根据您在文件中读取的内容分配调试值...

    private ByteArrayOutputStream getAssetFileAsByteArrayOutputStream(String filename)
    {
    AssetManager assetManager = this.getAssets();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();//  OutputStream(helper);
    try
    {
        final InputStream assetFile = assetManager.open(filename, AssetManager.ACCESS_RANDOM);
        byte readBuffer[] = new byte[1024 * 64];    //64kB
        int byteCount;
        while ((byteCount = assetFile.read(readBuffer)) > 0)
            byteStream.write(readBuffer, 0, byteCount);
        byteStream.flush();
        //          copiedFileStream.close();
    } catch (IOException e)
    {
    }
    return byteStream;
    }
    

然后在初始化最终(const)值之前要么放置一个静态块

  static 
  {
       //read file
       //get the value you want
  }
  public final static Variable myVar = valFromFile ? "DEBUG" : "NORMAL";

或者只是将最终变量的初始化移动到构造函数中,您可以在那里初始化最终变量。