Short answer – pretty simple. Thanks to QtAndroidExtras
First we need to add to your .pro file:
android: QT += androidextras
then add simple class to your codebase. Header:
#ifndef VIBRATOR_H #define VIBRATOR_H #include <QObject> #if defined(Q_OS_ANDROID) #include <QAndroidJniEnvironment> #include <QAndroidJniObject> #endif class Vibrator : public QObject { Q_OBJECT public: explicit Vibrator(QObject *parent = 0); signals: public slots: void vibrate(int milliseconds); private: #if defined(Q_OS_ANDROID) QAndroidJniObject vibratorService; #endif }; #endif // VIBRATOR_H
and the code:
#include "vibrator.h" #include <QDebug> Vibrator::Vibrator(QObject *parent) : QObject(parent) { #if defined(Q_OS_ANDROID) QAndroidJniObject vibroString = QAndroidJniObject::fromString("vibrator"); QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject appctx = activity.callObjectMethod("getApplicationContext","()Landroid/content/Context;"); vibratorService = appctx.callObjectMethod("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", vibroString.object<jstring>()); #endif } #if defined(Q_OS_ANDROID) void Vibrator::vibrate(int milliseconds) { if (vibratorService.isValid()) { jlong ms = milliseconds; jboolean hasvibro = vibratorService.callMethod<jboolean>("hasVibrator", "()Z"); vibratorService.callMethod<void>("vibrate", "(J)V", ms); } else { qDebug() << "No vibrator service available"; } } #else void Vibrator::vibrate(int milliseconds) { Q_UNUSED(milliseconds); } #endif
now you have to expose the class to QML:
#include "vibrator.h" ... Vibrator vibrator; engine.rootContext()->setContextProperty("Vibrator", &vibrator);
voila! its ready to use!
Vibrator.vibrate(500)
Enjoy