目录
- 简述
- Qt引入Android模块
- Java示例
- Cpp与java交互
简述
我做了一个小例子,来实现了 C++与Java之间的交互。
该示例是以整形和字符型举例说明,用QAndroidJniObject类的callStaticMethod方法进行与Java交互
Qt引入Android模块
首先要在Pro中加入Android开发模块
QT += androidextras
Java示例
可以先看一下我写的java简单案例(为了方便演示都做成静态了):
package com.demo.cppandjava;
public class democppandjava
{
private static int tmpNum = 1;
private static String tmpStr = "123";
public static void setInt(int num) {
tmpNum = num;
}
public static int getInt() {
return tmpNum;
}
public static void setString(String str) {
tmpStr = str;
}
public static String getString() {
return tmpStr;
}
}
Cpp与java交互
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pbSet_clicked();
void on_pbGetInt_clicked();
void on_pbGetStr_clicked();
private:
Ui::MainWindow *ui;
private:
//Cpp与java交互
void cppAssignmentJavaInt(int num);
int cppUseJavaToInt();
void cppAssignmentJavaString(QString str);
QString cppUseJavaToString();
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAndroidJniObject>
#include <QAndroidJniEnvironment>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::cppAssignmentJavaInt(int num)
{
#ifdef Q_OS_ANDROID
QAndroidJniObject::callStaticMethod<void>(
"com/demo/cppandjava/democppandjava",
"setInt",
"(I)V",
num);
#endif
}
int MainWindow::cppUseJavaToInt()
{
#ifdef Q_OS_ANDROID
return QAndroidJniObject::callStaticMethod<jint>("com/demo/cppandjava/democppandjava", "getInt");
#endif
}
void MainWindow::cppAssignmentJavaString(QString str)
{
#ifdef Q_OS_ANDROID
QAndroidJniObject strTMP = QAndroidJniObject::fromString(str);
QAndroidJniObject::callStaticMethod<void>(
"com/demo/cppandjava/democppandjava",
"setString",
"(Ljava/lang/String;)V",
strTMP.object<jstring>());
#endif
}
QString MainWindow::cppUseJavaToString()
{
#ifdef Q_OS_ANDROID
QAndroidJniObject str = QAndroidJniObject::callStaticObjectMethod("com/demo/cppandjava/democppandjava",
"getString",
"()Ljava/lang/String;");
return str.toString();
#endif
}
void MainWindow::on_pbSet_clicked()
{
int num = ui->spinBox->text().toInt();
QString str = ui->lineEdit->text();
cppAssignmentJavaInt(num);
cppAssignmentJavaString(str);
}
void MainWindow::on_pbGetInt_clicked()
{
ui->lText->setText(QString::number(cppUseJavaToInt()));
}
void MainWindow::on_pbGetStr_clicked()
{
ui->lText->setText(cppUseJavaToString());
}
整型是简单的,字符型稍稍要绕一下。要注意"()Ljava/lang/String;"这里有个分号哦!~