Force Screen Orientation on Android



  • Hello,
    I am currently developing an Android application. The application is, for most of the screens, meant to be used in portrait orientation, but there are a couple of screens that require the landscape orientation. What I would like to achieve is the application to modify the screen orientation base on the screen that is displayed. Kinda like what the youtube app does when you switch to full screen.
    Is it there any way to achieve this behavior? If yes, which is the best way?
    Thanks everybody.


  • Moderators

    For the whole app beginning from the startup see this.

    If you want to change it dynamically during runtime i am afraid you need to do so via JNI. See this. (setRequestedOrientation on the Activity)



  • Thanks raven for the reply. Yes I did already see the post about the AndroidManifest.xml but since the app will have to rotate at runtime I will have to follow the JNI way.



  • It's not so challenging. Use JNI as following simple implementation:

    void AndroidHelper::setScreenOrientation(int orientation)
    {
        QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
        if ( activity.isValid() )
        {
            activity.callMethod<void>
                    ("setRequestedOrientation" // method name
                     , "(I)V" // signature
                     , orientation);
        }
    }
    
    

    Don't forget to edit .pro file and add

    android {
        QT += androidextras
        SOURCES += androidhelper.cpp #my android specific cpp file
        HEADERS += androidhelper.h   #my android specific header file
    }
    


  • Thanks seyed, your solution is working, but i had to modify it slightly as it was giving me a compile error on this line

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

    So I changed it with this:

    QAndroidJniObject activity = QtAndroid::androidActivity();
    

    And it is working perfectly
    Thanks everybody for the help


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.