java - 在 Eclipse 中的 Android 项目中使用预处理器

标签 java android eclipse c-preprocessor

我正在尝试在 Eclipse 的 Android 项目中使用像 #ifdef 这样的预处理器。我对这个主题做了一些研究,发现了这个链接:Java Preprocessing Using Eclipse ,这可能让我在 Android 项目中使用预处理器。

但是,在我尝试构建该项目后,它声称诸如 package android.* 之类的内容不存在。因此,找不到任何 Android API。

那么,我应该如何在构建路径中添加这些库?实际上,android.jar 文件已经位于 Java 构建路径下。为什么 Eclipse 仍然这么声称?

还有其他方法可以让我在 Eclipse 构建的 Android 项目中使用预处理器吗?

最佳答案

您正在使用 Java 编程,而不是 C/C++。 Android 开发不需要使用预处理器。


编辑:

My problem is we developed an Android app with USB functionality which is supported only by Android 3.1+. So, some of the USB libraries are imported, what I want is those imported libraries could be commented out using #ifdef, if we could, when we build the project for Android 2.2 or 2.3, etc. Is there any other workaround for this?

要使用您提到的类/方法,您必须针对 Android SDK 版本 3.1 或更高版本构建应用程序。但是,您还必须确保运行 3.0 或更低版本的设备在运行时不会使用这些类/方法,因为这样做会导致 ClassNotFound 异常。

这里的关键要点是您需要在运行时执行这些检查。由于您的应用程序仅针对所有设备编译一次,因此预处理器无法阻止此类事件的发生。相反,您需要在代码中明确防止这种情况发生。这通常是通过基本的 if-else 语句来完成的。例如,

if (Build.VERSION_CODES.HONEYCOMB_MR1 >= Build.VERSION.SDK_INT) {
    // then you are on a device running android 3.1+ and it is
    // safe to make use of the new classes/methods
} else {
    // otherwise, you are running on a device running android 3.0
    // or lower. you should not make use of the new classes/methods.
}

编辑#2:

回应比尔的评论,内容如下:

Thank you, Alex. I built my project agaist 3.1, deployed it on 2.2 and run it. One last thing I am not quite sure I understand is I could debug the part of the code referred by the Android 3.1 on the Android 2.2 OS. Here is my explanation: after being built against 3.1, Java code is converted to machine code and HONEYCOMB_MR1 is just an integer although HONEYCOMB_MR1 is not present in 2.2, when I debugged it, the debugger goes to the line of HONEYCOMB_MR1, fetches that integer and compares with SDK_INT. In this way, the code could still be debugged although HONEYCOMB_MR1 is only in 3.1 SDK. Is that correct? Thanks.

我认为你的理解是正确的。更准确的推理是,HONEYCOMB_MR1 被标记为 static final。由于变量是不可变常量(即它的值永远不会改变),因此当您编译 .apk 时,整数会被硬编码到字节码中。因此,当您的 2.2 设备到达 if 语句时,它会检查是否 12 > 8,从而避免运行时搜索 HONEYCOMB_MR1(失败) >.

当您开发 Android 应用程序时,这种情况实际上经常发生。例如,此行为也解释了为什么您可以使用 MATCH_PARENT (在 2.2 中引入)在“技术上”应仅支持 FILL_PARENT 的设备上。两个常量的值都是-1;因此,当您在 Froyo 之前的设备上运行使用 MATCH_PARENT 的应用时,一切都会按预期工作。

关于java - 在 Eclipse 中的 Android 项目中使用预处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746436/

相关文章:

java - 项目缺少所需的库 [Eclipse]

java - Eclipse导入莫名其妙没有解决

java - 尝试 Catch 或 boolean 检查

ISA Server 2006 的 Java HttpSession 问题

java - 如何在 Android TextView 中显示来自 Firebase 的消息列表?

android - 从命令行查询 Android 内容提供程序(adb shell)

java - 尝试安装 eclipse,但我得到 "Java was started but returned exit code = 1"

java - Grails/Java new Date() 在 GSP 中不同

java - 套接字编程服务器套接字超时

android - 如何在 Recyclerview 交错网格布局中使用 Picasso 加载图像之前设置 ImageView 的高度和宽度