从QT / C ++调用自己的非静态java方法

时间:2018-02-20 11:22:29

标签: java android qt java-native-interface

我试图从QT / C ++调用我自己的Java类的非静态方法callNative,但是我收到以下错误:

W System.err:java.lang.NoSuchMethodError:没有非静态方法“Lorg / qtproject / qt5 / android / bindings / QtActivity; .callNative()V;”

以下是java类的代码:

package com.ieio.finger;


import static java.lang.System.out;

public class Finger extends org.qtproject.qt5.android.bindings.QtActivity {
    public void callNative()
        {
            System.out.println("I am in Java");
        }
}

这里是C ++代码 finger.h

#ifndef FINGER_H
#define FINGER_H

#include <QObject>

class finger : public QObject
{
    Q_OBJECT
public:
    explicit finger(QObject *parent = nullptr);
    Q_INVOKABLE void call_java();
signals:

public slots:
};

#endif // FINGER_H

finger.cpp:

#include <QtAndroidExtras/QAndroidJniObject>
#include <QtAndroidExtras/QtAndroid>
#include "finger.h"


finger::finger(QObject *parent) : QObject(parent)
{

}

void finger::call_java()
{
    qDebug()<< "call java";
    QtAndroid::androidActivity().callObjectMethod("callNative","()V;");
    qDebug()<< "called java";
}

main.cpp中:

#include <QGuiApplication>
#include <QQmlApplicationEngine>

#include <finger.h>

    int main(int argc, char *argv[])
    {    
        QGuiApplication app(argc, argv);

        QQmlApplicationEngine engine;
        qmlRegisterType<finger>("io.qt.ieio.finger", 1, 0, "Finger");

        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        if (engine.rootObjects().isEmpty())
            return -1;

        return app.exec();
    }

和qml:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

import io.qt.ieio.finger 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Finger
    {
        id:myFinger
    }

    Button {
        id: button
        x: 234
        y: 284
        text: qsTr("Button")
        onClicked: {
            myFinger.call_java()
        }
    }
}

为什么我会得到 java.lang.NoSuchMethodError

1 个答案:

答案 0 :(得分:0)

最终我找到了一个解决方案: 我改变了方法:

void finger::call_java()
{
    qDebug()<< "call java";
    QtAndroid::androidActivity().callObjectMethod("callNative","()V;");
    qDebug()<< "called java";
}

in

void finger::call_java()
{
    qDebug()<< "call java";
    QtAndroid::runOnAndroidThread([]{
        QAndroidJniObject myJavaObject("com/ieio/finger/Finger");
        myJavaObject.callMethod<void>("callNative","()V");
    });
    qDebug()<< "called java";
}