1

I'm deploying Android app using Qt.

I'd like to make the phone vibrate. So I try to execute this code using QAndroidJniObject.

Java code:

import android.os.Vibrator;
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);

C++ Qt code:

QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");

if ( activity.isValid() )
{
    QAndroidJniObject serviceName = QAndroidJniObject::fromString("android.content.Context.VIBRATOR_SERVICE");
    if ( serviceName.isValid() )
    {
        QAndroidJniObject vibrator = activity.callObjectMethod("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;",serviceName.object<jobject>());
        if ( vibrator.isValid() )
        {
            vibrator.callMethod<void>("vibrate", "(J)V", 1000);
        }
        // vibrator is actually not valid!
    }
}

vibrator.isValid() returns false and I cannot figure out why....It's not my first time trying to do this kind of stuff, but here, I can't make it work.

Note: My app has android.permission.VIBRATE set

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151

1 Answers1

1

From what I could gather from the documentation, QAndroidJniObject::fromString returns an object wrapping a Java string with the contents that you gave to fromString.

So what you're doing right now is as if you had done the following in Java:

Object vibrator = getSystemService("Context.VIBRATOR_SERVICE");

when what you really want is:

Object vibrator = getSystemService(Context.VIBRATOR_SERVICE);

So instead of using QAndroidJniObject::fromString you probably ought to be doing something like this:

QAndroidJniObject serviceName = 
    QAndroidJniObject::getStaticObjectField<jstring>(
        "android/content/Context",
        "VIBRATOR_SERVICE");

It's possible that you need to delete the local reference to serviceName afterwards.

jpo38
  • 20,821
  • 10
  • 70
  • 151
Michael
  • 57,169
  • 9
  • 80
  • 125
  • Thanks for your reply, I cannot make this piece of code compile with Qt 5.2.1. Error is `undefined reference to '_jstring* QAndroidJniObject::getStaticField<_jstring*>(char const*, char const*)` – jpo38 Apr 15 '15 at 08:28
  • Oops. That should probably be `getStaticObjectField` instead of `getStaticField`. – Michael Apr 15 '15 at 08:32
  • By the way, the phone does not vibrate :-( even if vibrate code is now reached and executed. Any idea? – jpo38 Apr 15 '15 at 11:40
  • vibrate call profile has to be changed from `(I)V` to `(J)V`. Edited the original post. – jpo38 Apr 27 '15 at 08:03