In questa pagina

Scambio linguistico Qt per Android

Mostra come richiamare codice Java e Kotlin da Qt e codice Qt da Java e Kotlin in un'applicazione Android.

App Android che mostra un messaggio e due pulsanti con le diciture "Hello Kotlin!" e "Hello Java!"

Fare clic su uno dei pulsanti per inviare una stringa alle classi Java e Kotlin e ricevere in risposta una stringa modificata.

Due schermate affiancate che mostrano la reazione dell'app ai pulsanti "Hello Kotlin" e "Hello Java"

Questo esempio illustra come aggiungere una classe Java personalizzata e una classe Kotlin personalizzata a un'applicazione Android e come richiamarle utilizzando le API di convenienza JNI in Qt. Viceversa, la classe Java e la classe Kotlin richiamano le funzioni Qt.

Esecuzione dell'esempio

È possibile eseguire l’esempio da:

Nota: questo esempio può essere eseguito solo su dispositivi Android.

Scambio di dati tra C++ e Java/Kotlin tramite i segnali Qt

Definiamo una classe Java personalizzata denominata JavaExchanger nel file JavaExchanger.java:

package org.qtproject.example.androidlanguageexchange;

public class JavaExchanger
{
    private long mCppExchanger;

    private native void connectToCppExchanger(long cppExchanger);
    private native void fromOther(long cppExchanger, String str);

    public JavaExchanger(long cppExchanger) {
        mCppExchanger = cppExchanger;
        connectToCppExchanger(cppExchanger);
    }
    public void fromCpp(int type, String str) {
        if (type == OtherLanguageType.Java.getCode()) {
            String msg = str + " And hello back to you from\nJava!";
            fromOther(mCppExchanger, msg);
        }
    }
}

Definiamo una classe Kotlin personalizzata denominata ` KotlinExchanger ` nel file ` KotlinExchanger.kt `:

package org.qtproject.example.androidlanguageexchange;

class KotlinExchanger(private val cppExchanger: Long) {

    private external fun connectToCppExchanger(cppExchanger: Long)
    private external fun fromOther(cppExchanger: Long, str: String)

    init {
        connectToCppExchanger(cppExchanger)
    }

    fun fromCpp(type: Int, str: String) {
        if (type == OtherLanguageType.Kotlin.code) {
            val msg = "$str And hello back to you from\nKotlin!"
            fromOther(cppExchanger, msg)
        }
    }
}

Entrambe queste classi accettano un intero lungo (long integer) che è semplicemente un QObject* convertito in long e, quando le funzioni fromCpp vengono chiamate a seguito dell’esecuzione della funzione connectToCppExchanger, modificano la stringa in entrata e la rinviano a fromOther insieme al long int.

Nel file di intestazione della classe C++ DataExchanger, dataexchanger.h, dichiariamo una semplice API C++ per lo scambio di dati tra C++ e Kotlin/Java. È costituita da un ` QObject ` con un segnale ` fromCpp ` inviato dal codice C++ in risposta ai pulsanti e un segnale ` fromOther ` che il codice Java/Kotlin utilizza per inviare una stringa al codice C++, come descritto in precedenza.

// A simple data exchanger. All this class does is convey semi-abstract data
// back and forth. For the purposes of this example, treat it as an opaque
// and not necessarily modifiable engine object that just happens to have
// a signal that's directly consumable by the code in other languages. The
// rest of the glue is done in OtherLanguageHandler.
class DataExchanger : public QObject
{
    Q_OBJECT
public:
    explicit DataExchanger(QObject *parent = nullptr);

    enum OtherLanguageType {Java, Kotlin};
signals:
    void fromCpp(OtherLanguageType type, const QString& str);
    void fromOther(const QString& str);
};

La chiamata al metodo Java utilizza ` QJniObject `, che si avvale delle API della Java Native Interface (JNI) per comunicare con Java/Kotlin. L’argomento di tipo `long integer` viene riconvertito nel tipo ` DataExchanger `, e il segnale ` fromCpp ` viene quindi collegato a una lambda che chiama la funzione ` fromCpp ` di Java/Kotlin.

// We provide this function so that the Java/Kotlin objects can register themselves
// as signal observers. The C++ code doesn't decide where and when that happens.
void connectToCppExchanger(JNIEnv* /*env*/, jobject thiz, jlong cppExchanger)
{
    DataExchanger* exchanger = reinterpret_cast<DataExchanger*>(cppExchanger);
    QJniObject androidExchanger(thiz);
    QObject::connect(exchanger, &DataExchanger::fromCpp, exchanger,
                     // Intentional, and important capture by value of the QJniObject.
                     // This keeps the underlying Java/Kotlin object alive until the call
                     // to it is performed.
                     [androidExchanger](DataExchanger::OtherLanguageType type, const QString& str) {
                         androidExchanger.callMethod("fromCpp",
                                                     static_cast<int>(type), str);
                     });
}

La chiamata a un metodo nativo della classe Java/Kotlin viene inoltrata alla classe ` DataExchanger `, convertendo nuovamente l’intero lungo in ` DataExchanger ` e chiamando quindi il segnale ` fromOther ` di quel tipo.

// The Java/Kotlin code calls this. The C++ code doesn't decide where and when
// it is called.
// Note that the function must be registered with the Qt native method
// registration facilities because it relies on the Qt wrapping that knows how to
// convert a jstring to a QString.
void fromOther(JNIEnv* /*env*/, jobject /*thiz*/,
                       jlong cppExchanger, const QString &str)
{
    DataExchanger* exchanger = reinterpret_cast<DataExchanger*>(cppExchanger);
    exchanger->fromOther(str);
}

Per assicurarci che i nostri pulsanti funzionino come previsto, aggiungiamo il seguente codice per innescare l’invio di una stringa a Java/Kotlin e per ricevere in ritorno la stringa modificata:

    QObject::connect(&javaButton, &QPushButton::clicked, &javaButton, [&]() {
        dataExchanger.fromCpp(DataExchanger::Java, "Hello!");
    });

    QObject::connect(&kotlinButton, &QPushButton::clicked, &kotlinButton, [&]() {
        dataExchanger.fromCpp(DataExchanger::Kotlin, "Hello!");
    });
    QObject::connect(&dataExchanger, &DataExchanger::fromOther,
                     &dataExchanger, [&](const QString& str) {
        fromOtherLabel.setText(str);
    });

Progetto di esempio su code.qt.io

Vedi anche Qt per Android.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.