gpt4 book ai didi

android - 如何使用 QAndroidJniObject 从 Qt 内部调用 Java 代码?

转载 作者:太空狗 更新时间:2023-10-29 14:11:49 33 4
gpt4 key购买 nike

从一个用 Qt Creator 创建的空 Qt for Android 项目开始,我如何执行原生 Java 代码?

例如,如果我有这个 java 方法:

class HelloJava {
public static String sayHello(int a, int b) {
return "Hello from Java, a+b=" + (a+b);
}
}

我有这个 Qt 方法,它应该调用 HelloJava.sayHello() 方法:

QString call_HelloJava_sayHello(int a, int b) {
// What goes in here?
}

我应该将 Java 代码放在项目中的什么位置,call_HelloJava_sayHello() 方法中包含哪些内容?

最佳答案

Qt doc在这个问题上非常冗长:

// Java class
package org.qtproject.qt5;
class TestClass
{
static String fromNumber(int x) { ... }
static String[] stringArray(String s1, String s2) { ... }
}


// C++ code

// The signature for the first function is "(I)Ljava/lang/String;"
QAndroidJniObject stringNumber = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/TestClass",
"fromNumber"
"(I)Ljava/lang/String;",
10);

// the signature for the second function is "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"
QAndroidJniObject string1 = QAndroidJniObject::fromString("String1");
QAndroidJniObject string2 = QAndroidJniObject::fromString("String2");
QAndroidJniObject stringArray = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/TestClass",
"stringArray"
"(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"
string1.object<jstring>(),
string2.object<jstring>());

所以你的函数的 sig 应该是 "(I;I;)Ljava/lang/String;"

还有这个:

ANDROID_PACKAGE_SOURCE_DIR: This variable can be used to specify a directory where additions and modifications can be made to the default Android package template. The androiddeployqt tool will copy the application template from Qt into the build directory, and then it will copy the contents of the ANDROID_PACKAGE_SOURCE_DIR on top of this, overwriting any existing files. The update step where parts of the source files are modified automatically to reflect your other settings is then run on the resulting merged package. If you, for instance, want to make a custom AndroidManifest.xml for your application, then place this directly into the folder specified in this variable. You can also add custom Java files in ANDROID_PACKAGE_SOURCE_DIR/src.

Note: When adding custom versions of the build files (like strings.xml, libs.xml, AndroidManifest.xml, etc.) to your project, make sure you copy them from the package template, which is located in $QT/src/android/java. You should never copy any files from the build directory, as these files have been altered to match the current build settings.

看来您需要指定它,java 文件会自动部署。

只需将其添加到您的 .pro 文件中(假设您的 java 源代码位于 /path/to/project/myjava/src:

android {
ANDROID_PACKAGE_SOURCE_DIR=$$_PRO_FILE_PWD_/android
QT += androidextras
}

_PRO_FILE_PWD_ 是一个将解析为项目目录的 qmake 变量。

关于android - 如何使用 QAndroidJniObject 从 Qt 内部调用 Java 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27094100/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com