Search code examples
javaandroidc++qtqtandroidextras

Changing orientation of a particular page in android


I am working on an android app in Qt and c++. My whole application has portrait orientation.But when i play a video i want to change the orientation to landscape, and after video ends it should again change to portrait.

So the question is How is it possible to set the screen to landscape or portrait modes in a Qt/C++ application for Android.


Solution

  • Screen orientation on Android can be changed using setRequestedOrientation Java function so you should call a Java function from your app. To run Java code in your Qt Android application you should use the Qt Android Extras module which contains additional functionality for development on Android.

    You can use JNI to call a Java function from C/C++ or callback a C/C++ function from Java.

    Here you could have it in a static Java method like :

    package com.MyApp;
    
    public class OrientationChanger
    {
        public static int change(int n)
        {
            switch(n)
            {
                   case 0:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                       break;
                   case 1:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                       break;                   
               }
        }
    }
    

    First you need to add this to your .pro file :

    QT += androidextras
    

    And Include the relevant header file :

    #include <QAndroidJniObject>
    

    You can then call this static Java function from your C++ code.

    To change the orientation to landscape mode :

    bool retVal = QAndroidJniObject::callStaticMethod<jint>
                            ("com/MyApp/OrientationChanger" // class name
                            , "change" // method name
                            , "(I)I" // signature
                            , 0);
    

    To change the orientation to portrait mode :

    bool retVal = QAndroidJniObject::callStaticMethod<jint>
                            ("com/MyApp/OrientationChanger" // class name
                            , "change" // method name
                            , "(I)I" // signature
                            , 1);