mafulechka
mafulechkaJuly 8, 2019, 5:21 a.m.

How to meet the new requirements of Google Play

Starting August 1st , Google Play will no longer accept new apps or app updates without a 64-bit version (unless native code exists at all, of course). For Qt users, this means that you need to create an additional APK containing 64-bit binaries.


Qt ships 64-bit binaries for Android (as of Qt 5.12.0), so technically meeting the new requirement is not much of a problem. But after discussing with users, it became clear that not everyone understands how to set up an application on Google Play that supports multiple architectures at the same time.

This call for help, combined with the fact that a new Windows work station is now being set up, provided an excellent opportunity to look at Qt Android application development in general. In this blog, we'll start with a clean slate and show you how to get started on Android, as well as how to publish an app that meets the Google Play requirements.

We will:

  • go through all the installation steps required to create a working environment;
  • describe the process of building an application for several architectures,
  • and show you how to upload your binaries to Google Play.

The first few parts may be familiar to many of you, so if you're bored and want to familiarize yourself with the main topic, feel free to skip to step 4.

Note about SDK versions

The Android SDK is under heavy development and is quite often not backwards compatible, causing integration issues with Qt. While we respond as quickly as possible to issues that arise due to changes or regressions in the SDK, a general rule of thumb is to wait before updating to the latest and greatest Android tools until you can adapt to incompatibility with Qt.

While there were some issues on other platforms as well, most of the issues we saw were related to Windows. Therefore, if you are on this host system, be especially careful to check for known good versions before setting up your environment.

We currently recommend using the following tools along with Qt 5.13.0:

• Android build tools (Android build tools) version 28
• Android NDK r19
• Java Development Kit 8

Step 1: Installing the JDK

Android is primarily a Java-based platform, and while you can write your Qt applications entirely in C++ and/or QML, you will need the Java Development Kit to compile the files that make the integration possible.

Please note that there is an incompatibility between the Android SDK Manager tool and later versions of the Oracle JDK, which makes the latest JDK versions unusable with the Android environment. To get around this, we recommend that you download JDK version 8 for use with Android.

You can use the official Oracle binaries or another option like the AdoptOpenJDK project.
Download and run the installer and install it in the default folder.

Step 2: Set up the Android environment

The second step is to get the actual Android development environment. Start by downloading and installing Android Studio . Scroll through the various "beta" and "canary" releases (versions) and you'll find the latest stable release.

Once Android Studio is installed, you can use it to install the “SDK Platform” . This is the actual collection of Java classes for a specific Android distribution. The first time you open Android Studio, you will be prompted to install the SDK framework. You can safely use the latest SDK, platform 29, which is the recommended default.

In addition to the SDK, we also need to install the NDK. This is a development kit used to cross-compile C++ code to run on Android. As mentioned above, we will be using Android NDK r19c and not the latest release as there are issues with Android NDK r20 causing compilation errors. The issue will be resolved in Qt 5.13.1 and Qt 5.12.5, so when you start using them, it's possible to upgrade to Android NDK r20.

And as a final step, we need to make sure we are using the 28.0.3 Android build tools version and not the latest version. Note that this is only an issue for Windows hosts.

In the initial Android Studio dialog, click Configure and then select SDK Manager . Click the SDK Tools tab and make sure the Show Package Details checkbox is checked. Under Android build tools make sure you deselect 29.0.0 and choose 28.0.3 instead.

This will remove the broken version of the build tools and install the older version. Click Apply to start the process, and when it's done, you'll have a working Android environment installed.

Step 3: Install Qt

We will be using Qt 5.13.0. If you haven't already, start by downloading the online installer from your Qt Account.

When running the installer, make sure you select the arm64-v8a and armv7a target architectures. These are the technical names, respectively, for the 64-bit and 32-bit versions of the ARM family of processors, which are the most commonly used processors on Android devices.

Note In particular, we will need Qt Purchasing for this example because it contains the application we plan to use as a demo. It can also be selected from the list.

When Qt has finished installing, launch Qt Creator and open Options . In the Devices section, go to the Android tab and select the directories where you installed the various packages in the previous steps.

If everything is set up correctly, Qt Creator will show a green checkmark and you will be ready to start Android development with Qt.

Step 4: Setting up the project in Qt Creator

For this example, we will use Qt Hangman . This is a small example we made to show how to make in-app purchases in a cross-platform way.

We will first open Qt Creator, which can be done from the welcome screen. Once it has been opened, Qt Creator will ask us to choose which versions of Qt we want to use to build it.

Select 64-bit and 32-bit versions of Qt and click Configure Project .

To meet the additional requirements on Google Play, we want to create two APKs, one for 32-bit devices and one for 64-bit devices. We need to configure each of them individually.

This screenshot shows an installation example for a 32-bit build. Important things to pay attention to:

• Use a different shadow build directory for each build.
• Make sure you select Release configuration .
• You must also check the Sign package checkbox to sign the package, otherwise the Google Play Store will reject it.

With the exception of the build directory, the setting for a 64-bit build should be the same. Select the 64-bit bundle on the left side and make the equivalent settings to it.

Step 5: Preparing the manifest

In addition, the two packages will require identical AndroidManifest.xml files, except for one detail: the version code of the two must be different. The version code can be almost anything you choose, but be aware that when an APK is installed on a device from the store, it will select the APK with the highest version code. As Qt user Fabien Chereau pointed out in a comment on the bug report, you generally want to set the version code of the 64-bit version higher than the 32-bit one, so that a device that supports both versions will prefer the 64-bit one.

As Felix Barz pointed out in the same thread, this can be automated in the project's .pro file. Here is a slightly modified version of his code:

defineReplace(droidVersionCode) {
        segments = $$split(1, ".")
        for (segment, segments): vCode = "$$first(vCode)$$format_number($$segment, width=3 zeropad)"

        contains(ANDROID_TARGET_ARCH, arm64-v8a): \
            suffix = 1
        else:contains(ANDROID_TARGET_ARCH, armeabi-v7a): \
            suffix = 0
        # add more cases as needed

        return($$first(vCode)$$first(suffix))
}

VERSION = 1.2.3
ANDROID_VERSION_NAME = $$VERSION
ANDROID_VERSION_CODE = $$droidVersionCode($$ANDROID_VERSION_NAME)

This trick converts the application's VERSION to an integer and adds a new digit, at the least significant end, to indicate the architecture. So, for example, for version 1.2.3, the version code would be 0010020030 for a 32-bit package and 0010020031 for a 64-bit package.

When you generate AndroidManifest.xml using the Build APK button in the project settings, it automatically pulls that version code from the project. Once you've done this and edited the manifest to get your application's package name and package name, the last step is to build the package: first you build with one of the two kits, and then you must activate the other kit and build again.

When you're done, you'll have two releaseable APK packages, one in each of the build directories you set up earlier. Relative to the build directory, the package will be in android-build\build\output\apk\release .

Note that for more efficient setup, you'll probably want to automate this process. This is also entirely possible since all the tools used by Qt Creator can be run from the command line. Look at the androiddeployqt documentation for more information.

Step 6: Publish the app on Google Play

The Google Play publishing page is pretty self-documenting, and there are a lot of good tutorials on how to do it, so we won't go through all the steps of filling out the form. Basically, just fill in all the requested information, provide the images you want, and make sure all the checkboxes in the left sidebar are green. You can add all kinds of content here, so take your time with it. In the end, this will affect the popularity of your application.

Once this is done, you can create a new release in the App Releases section and upload your APKs there.

It's worth noting that on first launch, you'll be prompted to allow Google Play to manage your app's signing key.

For now, you will need to opt out of this by selecting Opt Out. To use this feature, the app must be in the new "Android App Bundle" format. It is not yet supported by Qt, but developers are also working on it. In fact, Bogdan Vatra of KDAB (which also maintains the Android to Qt port) has already posted a patch that solves the biggest challenge of getting this support.

When we receive support, it will make the release process more convenient. With the AAB format, Google Play will generate optimized APKs for various architectures, but for now we have to do it manually by configuring multiple bundles and creating multiple APKs as described earlier in this guide.

When two APKs have been uploaded to a release, you should see a list like the one in the image above: two separate APKs, each covering one native platform. Expanding each of the entries, you can see what the “Differentiating APK details” are. These criteria are used to select one from the other when the device downloads an APK from the Google Play Store (Google Play Store). In this case, the differentiating part must be the native platform.

So all you have to do is build and release a Qt application on Google Play with both 32-bit and 64-bit binaries. Once the APKs are uploaded, you can click Publish and wait for Google Play to do its automation. And if you have 32-bit apps in the store at the moment, make sure you update to 64-bit well before August 2021 as that's when incompatible apps will no longer be served on 64-bit devices, even if they're also support 32-bit binaries.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Vladimir Sergeevich
  • July 8, 2019, 5:49 a.m.

Спасибо. Я ждал эту информацию.
Правда требования не такие уж новые. Я первое письмо от гугла получил почти год назад, а еще у вас на форуме тему создавал: https://evileg.com/ru/forum/topic/909/ (думаю, ее как-то стоит слить со статьей или хотя бы ссылку поставить, т.к. по запросу google android 64 bit она одна из первых в выдаче гугла).

Evgenii Legotckoi
  • July 8, 2019, 5:52 a.m.

К сожалению, нет возможности оперативно разбираться в подобных вещах самостоятельно. Объём проработки информации слишком большой для маленького информационного ресурса. Но как только на блоге Qt вышла подобная полезная статья, так сразу сделали перевод.

Andrei Yankovich
  • July 20, 2019, 2:41 p.m.

Очень полезная информация, увы уже выкинул поддержку 32 битных бедняг.

Evgenii Legotckoi
  • July 21, 2019, 6:03 a.m.

да, наверное, 32-х разрядную поддержку уже давно поа было выкинуть. К слову, у вас много проектов под Android? Часто много где вижу вопросы о том, пишет ли кто-то вообще на Qt под мобильные системы. При этом вижу мнения, что под мобильные системы стоит писать вообще на нативных средствах. При этом у меня складывается мнение, что проекты есть и их не мало, просто народ об этом обычно не трубит на каждом повороте.

SS
  • April 24, 2021, 9:09 a.m.
  • (edited)

Добрый день.
Спасибо вам огромное за вашу статью!
только начинаю изучать QT под Андроид
4 дня потратил на то чтобы подобрать версию QT которая наконец то скомпилирует мне на windows.
Уже думал вторую операционку ставить Линукс.
Но благодаря вашей статье -поставив все строго как вы описывали - все заработало.

ЯО
  • June 17, 2021, 3:37 p.m.

Ку всем! Вопрос! Как с помощью JNI вызвать оплату на android устройстве? Попробовал Qt Purchasing вроде пошло... но android пишет что библиотека устарела. В qt6 пока поддержки purchasing нет. Работать начал с Qt 5.15

Добрый день! Честно, не подскажу. Вообще я мог бы вам посоветовать посмотреть в сторону Qt-based фреймворка Felgo. У них сейчас в бесплатном тарифе есть как поддержка покупок внутри приложения, так и поддержка рекламных блоков.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 10:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 10:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 4:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks