Qt on Android:使用JNI與第三方j(luò)ar包
if(m_nativeNotify == null){
m_nativeNotify = new ExtendsQtNative();
}
m_nativeNotify.OnDownloaded(result, uri, data);
}
}
ExtendsQtNative.java:
? 1
2
3
4
5
6
7package an.qt.useJar;
import java.lang.String;
public class ExtendsQtNative
{
public native void OnDownloaded(int result, String url, String content);
}
基本思路是醬紫的:
Qt調(diào)用java的downloadWebPage,Java代碼使用asynchttpclient下載一個(gè)網(wǎng)頁,然后調(diào)用ExtendsQtNative通知Qt C++代碼。
C++代碼
分兩部分,一部分是實(shí)現(xiàn)JNI方法。另一部分是調(diào)用Java類的方法。
實(shí)現(xiàn)JNI方法并注冊(cè)
先看與ExtendsQtNative對(duì)應(yīng)的JNI實(shí)現(xiàn),在main.cpp中,都列出吧:
61#include widget.h
#include
#include
#include
#include
#include ../simpleCustomEvent.h
#include
QObject *g_listener = 0;
// result: -1 failed; 1 success; 0 busy;
static void onDownloaded(JNIEnv *env, jobject thiz,int result, jstring uri, jstring data)
{
QString qstrData;
const char *nativeString = env->GetStringUTFChars(data, 0);
qstrData = nativeString;
env->ReleaseStringUTFChars(data, nativeString);
QCoreApplication::postEvent(g_listener, new SimpleCustomEvent(result, qstrData));
}
bool registerNativeMethods()
{
JNINativeMethod methods[] {
{OnDownloaded, (ILjava/lang/String;Ljava/lang/String;)V, (void*)onDownloaded}
};
const char *classname = an/qt/useJar/ExtendsQtNative;
jclass clazz;
QAndroidJniEnvironment env;
QAndroidJniObject javaClass(classname);
clazz = env->GetObjectClass(javaClass.object
qDebug() find ExtendsQtNative - clazz;
bool result = false;
if(clazz)
{
jint ret = env->RegisterNatives(clazz,
methods,
sizeof(methods) / sizeof(methods[0]));
env->DeleteLocalRef(clazz);
qDebug() RegisterNatives return - ret;
result = ret >= 0;
}
if(env->ExceptionCheck()) env->ExceptionClear();
return result;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
SimpleCustomEvent::eventType();
registerNativeMethods();
Widget w;
g_listener = qobject_cast
w.show();
return a.exec();
}
注冊(cè)JNI方法,設(shè)置一個(gè)全局的對(duì)象接收通知。具體的,參考Qt幫助來理解。
調(diào)用Java方法
對(duì)Java方法的調(diào)用在Widget.cpp中。直接看代碼吧。
widget.h:
? 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
#include
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
bool event(QEvent *e);
public slots:
void onGet();
private:
QLineEdit * m_urlEdit;
QTextEdit * m_resultView;
QLabel * m_stateLabel;
};
#endif // WIDGET_H
都是界面相關(guān)的,沒什么好說的??磜idget.cpp:
? 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71#include widget.h
#include
#include
#include ../simpleCustomEvent.h
#include
#include
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
評(píng)論