QML: Get Android apk package info


All the information stored inside apk AndroidManifest.xml file can be extracted using dedicated Android API. Using JNI through C++ Qt layer is possible to get these info and pass them to the QML level.




Full example code can be found here

Thee is no need detailed explanations since code is very simple. Using JNI is possible to call the native Android APIs for extract the info required. Please note in this example only few information has been "converted" from java to C++ but using this code you have available the full Android PackageInfo object containing all the info regarding your apk (official documentation here). This mean if you need additional info you just have to add code lines for convert the field you require from packageInfo object as follow:

QVariantMap AndroidInterface::getApkInfo()
{
    QAndroidJniObject activity = QtAndroid::androidActivity();
    QAndroidJniObject packageName, packageManager, packageInfo;
    QAndroidJniEnvironment env;
    QVariantMap info;

    packageManager = activity.callObjectMethod("getPackageManager", "()Landroid/content/pm/PackageManager;");
    packageName = activity.callObjectMethod("getPackageName", "()Ljava/lang/String;");

    packageInfo = packageManager.callObjectMethod("getPackageInfo",
                                                  "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",
                                                  packageName.object<jstring>(),
                                                  0
                                                  );
    if(!env->ExceptionCheck())
    {
        info["packageName"] = packageInfo.getObjectField<jstring>("packageName").toString();
        info["versionName"] = packageInfo.getObjectField<jstring>("versionName").toString();
        info["versionCode"] = packageInfo.getField<jint>("versionCode");
    }
    else
    {
        env->ExceptionClear();
    }

    return info;
}

Once collected the required info you can pass to the QML layer using QVariantMap that will be automatically converted into a javascript structure and used as follow:

Window {
    visible: true
    width: 640
    height: 480
    color: "#E0F8F7"

    Component.onCompleted: {
        var info = android.getApkInfo();
        packageName.text = info.packageName;
        versionName.text = info.versionName;
        versionCode.text = info.versionCode;
    }

    Column {
        anchors.centerIn: parent
        spacing: 10

        Label { text: "Package Name:" }
        Label { color: "red"; id: packageName }
        Label { text: "Version Name:" }
        Label { color: "red"; id: versionName }
        Label { text: "Version Code:" }
        Label { color: "red"; id: versionCode }
    }
}

The result is here:

Comments

Popular posts from this blog

Access GPIO from Linux user space

Launch an app from Android shell terminal