Qt+Android:不同项目通用的java文件的位置



在Qt for Android中,您的项目中包含java文件。该位置是使用项目文件中的变量ANDROID_PACKAGE_SOURCE_DIR配置的。

该位置还包含特定于项目的其他文件(资源等)。

但是,如果这些java文件对于不同的项目是通用的,那么您应该有单独的副本,在相应的ANDROID_PACKAGE_SOURCE_DIR 中的每个项目上都有一个副本

我的问题是,是否有人知道一种方法,可以指定一个独立于项目位置的java文件目录。

我对在Qt中开发Android应用程序还相当陌生,但最近我开始了这段旅程,遇到了与你完全相同的问题;我写了一些常见的C++/Java代码,希望在几个不同的应用程序之间共享。C++代码很简单(共享库),但正如您所说的Java代码,我不希望在每个项目目录中都有相同Java代码的副本。

这花了一些时间,但我找到了一种很容易做到的方法

在编译/链接C++代码后编译Qt Android项目时,会运行一个编译Java代码的ANT脚本(因此,您只需要将Java源文件而不是编译的JAR文件粘贴在src文件夹中)。

ANT脚本是Android SDK的一部分,默认情况下,它会在src文件夹中查找并编译在那里找到的任何Java文件。因此,您真正需要确保的是,在运行ANT脚本之前,您想用作应用程序一部分的所有Java文件都位于该文件夹中。

ANDROID_PACKAGE_SOURCE_DIR变量告诉qMake在哪里可以找到需要复制到ANDROID-build文件夹的文件(包括任何特定于项目的Java代码),但我们想要的是一个自定义目标,该目标在ANT脚本执行前运行一段时间,以手动将我们的通用Java文件复制到src文件夹,这样它们也可以编译到应用程序中。

为了在我的*.pro文件中做到这一点,我添加了以下内容:

# This line makes sure my custom manifest file and project specific java code is copied to the android-build folder
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
# This is a custom variable which holds the path to my common Java code
# I use the $$system_path() qMake function to make sure that my directory separators are correct for the platform as you need to use the correct separator in the Make file (i.e.  for Windows and / for Linux)
commonAndroidFilesPath = $$system_path( $$PWD/../CommonLib/android-sources/src )
# This is a custom variable which holds the path to the src folder in the output directory. That is where they need to go for the ANT script to compile them.
androidBuildOutputDir = $$system_path( $$OUT_PWD/../android-build/src )
# Here is the magic, this is the actual copy command I want to run.
# Make has a platform agnostic copy command macro you can use which substitutes the correct copy command for the platform you are on: $(COPY_DIR)
copyCommonJavaFiles.commands = $(COPY_DIR) $${commonAndroidFilesPath} $${androidBuildOutputDir}
# I tack it on to the first target which exists by default just because I know this will happen before the ANT script gets run.
first.depends = $(first) copyCommonJavaFiles
export(first.depends)
export(copyCommonJavaFiles.commands)
QMAKE_EXTRA_TARGETS += first copyCommonJavaFiles

当您运行qMake时,生成的Make文件将具有以下内容:

first: $(first) copyCommonJavaFiles
copyCommonJavaFiles:
    $(COPY_DIR) C:UsersbvanderlaanDocumentsGitHubMyProjectMyProjectApp..CommonLibandroid-sourcessrc C:UsersbvanderlaanDocumentsGitHubbuild-MyProject-Android_for_armeabi_v7a_GCC_4_9_Qt_5_4_1-DebugMyProjectApp..android-buildsrc

所以现在,当我构建我的通用C++时,它会被链接为一个共享库,在ANT脚本编译所有Java代码并将我可能拥有的任何特定于项目的Java代码复制到我的应用程序之前,我的通用Java代码会被复制到src目录中。这样就不需要在源代码树的多个位置保存Java文件的副本,也不需要在编译之前使用外部构建脚本/工具来设置工作空间。

我希望这能回答你的问题,对你有用。

直到下一次富有想象力地思考和创造性地设计

最新更新