How To Integrate
- Place QtAndroidTools lib to your project dir and include it in .pro file
include(QtAndroidTools/QtAndroidTools.pri)
- Assign in you .pro file varialble ANDROID_PACKAGE_SOURCE_DIR before include QtAndroidTools/QtAndroidTools.pri, for ex.
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
- In the main() body insert the call for initialize the library
QtAndroidTools::InitializeQmlTools();
IMPORTANT NOTE: The library .pri check if java sources are already present into android/src folder, if no copy the library files. In case you are updating the library remember to remove these java files to be sure having always the new java versions code.
ApkExpansionFiles
Help in manage the apk expansion files download
Apk upload size limit is currently 100MB but in case your app require more data the Android Console allow to "attach" two files connected to your app. Official documentation about this feature is here, is strongly suggested to read it for allow a better comprension about how to use this tool. Usually the expansion files are downloaded by the Google Play together with the main app but in case the user delete it or some other problem occurs and the file will not be available anymore the app have to download again usually at startup. In this phase is required the java code of the two libraries explained in the documentation, the Google Play Licensing Library and the Google Play APK Expansion Library. However, at the time this post was written, there are a couple of problems. The official documentation suggest to get these libraries through the Android SDK Manager and then create two modules using the libraries just obtained. The problem here is the code of there libraries is very very old and use some deprecated dependencies making difficult the compilation using Qt Creator. It exist an updated version of these two libraries always developed by Google here and here. However also these two latest libraries are not supported by a long time and doesn't work very well in the latest versions of Android, from 8 and above. For this reasons this tool implement the two updated version community supported better-apk-expansion and better-licensing that make the same job but are updated enough for support the new notify feature of Android 8. I only made a small modify for support the Qt multi language engine. In the version inside the tool the java library ask to the C++ level for the info text to use in the Android notify label allowing the Qt language selector to select the correct language string.
Remember for have the download library working as expected you have to set the following permission in your app:
<manifest ...> <!-- Required to access Google Play Licensing --> <uses-permission android:name="com.android.vending.CHECK_LICENSE" /> <!-- Required to download files from Google Play --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Required to keep CPU alive while downloading files (NOT to keep screen awake) --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- Required to poll the state of the network connection and respond to changes --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Required to check whether Wi-Fi is enabled --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <!-- Required to read and write the expansion files on shared storage --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
Also note, in case your Android app is target for version 23 or above you have to explicitly ask for the WRITE_EXTERNAL_STORAGE permission cause this is one of the "dangerous" permission. You can use the other AppPermissions tool available in this library. Also you have to correctly the various part of the library by addicting these lines inside your AndroidManifest.xml file:
<application> ..... <service android:name="com.google.android.vending.expansion.downloader.impl.DownloaderService" android:enabled="true"/> <receiver android:name="com.google.android.vending.expansion.downloader.impl.DownloaderService$AlarmReceiver" android:enabled="true"/> </application>
Please note from now it's assumed you have read the documentation and already know the type and the format of expansion files is possible to upload and how the licensing engine work. First initialization is the following:
QtAndroidApkExpansionFiles.base64PublicKey = "app_public_key_here"; QtAndroidApkExpansionFiles.salt = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; QtAndroidApkExpansionFiles.main.version = 1; QtAndroidApkExpansionFiles.main.size = 123456789; QtAndroidApkExpansionFiles.patch.version = 1; QtAndroidApkExpansionFiles.patch.size = 123456789;
The base64PublicKey can be found in the Android Console app info and the salt is a random array of 20 bytes you have to generate by yourself. This is required for encrypt your data stored of the server. Version and size is required for identify your main and patch file. You can upload only the main file (and then you have to set only the main fields), these info are used to check if the current expansion files eventually already present in the device correspond in term of version number and file size.
Once configured the basic info you can check the operation to make by calling the following function:
QtAndroidApkExpansionFiles.startDownloadFiles()
If this function will return:
QtAndroidApkExpansionFiles.APKEF_NO_DOWNLOAD_REQUIRED
mean your expansion file are already available in the device than there is nothing to do, you can proceed with the app execution. In case of return:
QtAndroidApkExpansionFiles.APKEF_DOWNLOAD_STARTED QtAndroidApkExpansionFiles.APKEF_LVL_CHECK_REQUIRED
mean the apk expansion files download is started than you have to manage the download progress info. A download notify will be showed in the system status bar but your app should also show a progress control to inform the user regarding the operation in progress and that he have to wait. All other return codes are basically error conditions, check the library sources to see all the possible error types.
During download phase the tool generate two signals updating you about current status as follow:
Connections {
target: QtAndroidApkExpansionFiles
onDownloadStateChanged: {
switch(newState)
{
case QtAndroidApkExpansionFiles.STATE_COMPLETED:
...
break;
case QtAndroidApkExpansionFiles.STATE_FAILED_UNLICENSED:
case QtAndroidApkExpansionFiles.STATE_FAILED_FETCHING_URL:
case QtAndroidApkExpansionFiles.STATE_FAILED_SDCARD_FULL:
case QtAndroidApkExpansionFiles.STATE_FAILED_CANCELED:
case QtAndroidApkExpansionFiles.STATE_FAILED:
...
break;
}
}
onDownloadProgress: {
var time = new Date(timeRemaining);
downloadProgressBar.to = overallTotal;
downloadProgressBar.value = overallProgress;
downloadSizeLabel.text = (overallProgress / (1024*1024)).toFixed(2) + "MB/" + (overallTotal / (1024*1024)).toFixed(2) + "MB";
downloadTimeLabel.text = "Time left: ";
if(timeRemaining > 1000 * 60 * 60)
downloadTimeLabel.text += ("0" + time.getHours()).substr(-2) + ":" + ("0" + time.getMinutes()).substr(-2);
else
downloadTimeLabel.text += ("0" + time.getMinutes()).substr(-2) + ":" + ("0" + time.getSeconds()).substr(-2);
}
}
onDownloadStateChanged have the newState param informing about the download state changed. Check the sources for all the possible values. onDownloadProgress report info about the download process like current size and time left. Once download completed or if your expansion files are already available is possible to retrieve the full path of both files by use the following functions:
QtAndroidApkExpansionFiles.mainFileName() QtAndroidApkExpansionFiles.patchFileName()
During download phase always is possible to abort, stop and restart download by using the functions below:
QtAndroidApkExpansionFiles.abortDownload() QtAndroidApkExpansionFiles.pauseDownload() QtAndroidApkExpansionFiles.continueDownload()
A specific note regarding the function getString(). It return an info string connected with the current download status and some other info. It's used internally to pass correct language string to the java library but you can use also for the main interface as in demo example.
AppPermissions
This tool allow to request Android app permissions in an easier way.
From Android version 23 (Marshmallow) there are a list of special permission called "dangerous" because are directly connected to personal data of the user like calendar, contacts list and so on (official documentation here). If your app is target for this version and above and your manifest file contains one of the dangerous permissions you have to explicitly get the user authorization for have such permission granted. In the demo app four of these dangerous permission will be requested as follow:
There are two functions for request permissions, one accept a list of permissions for allow a unique request for all and another can be used to ask for a single permission only. In this example the multiple request function will be used as follow:
import QtAndroidTools 1.0 ... readonly property var permissionsNameList: ["android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_CALENDAR","android.permission.READ_PHONE_STATE","android.permission.READ_CONTACTS"] ... QtAndroidAppPermissions.requestPermissions(permissionsNameList)
The call of this function will have a result to show the system message informing the user the app require the specific permissions and ask for approval:
Once the user will finish to make the choice a signal will be generated with a list of struct as param as follow:
Connections {
target: QtAndroidAppPermissions
onRequestPermissionsResults: {
for(var i = 0; i < results.length; i++)
{
if(results[i].granted === true)
{
setPermissionGranted(results[i].name, true);
}
else
{
if(QtAndroidAppPermissions.shouldShowRequestPermissionInfo(results[i].name) === true)
{
if(results[i].name === permissionsNameList[0])
requestPermissionWRITE_EXTERNAL_STORAGE.open();
else if(results[i].name === permissionsNameList[1])
requestPermissionREAD_CALENDAR.open();
else if(results[i].name === permissionsNameList[2])
requestPermissionREAD_PHONE_STATE.open();
else if(results[i].name === permissionsNameList[3])
requestPermissionREAD_CONTACTS.open();
}
else
{
setPermissionGranted(results[i].name, false);
}
}
}
}
}
Each item in the list contain the param name containing the permission string name and the boolean field granted informing if the user allowed the app to get the permission or not. Please note, if you app will be target under version 23 this signal will be emitted immediately without show any messagebox and, obviously, with all the permission automatically granted. This for allow the code working in the same way independently by the Android target version selected. In case the user don't granted a permission this special call is used in the code:
QtAndroidAppPermissions.shouldShowRequestPermissionInfo(...)
This function is quite particular and return true only in the case a first attempt to ask to permission has been denied. Basically it "suggest" to show a message to the user explaining why your app need the specific permission before retry to ask for permission again:
Once explained the reasons you can ask again for the same permission by using this time the single request function:
QtAndroidAppPermissions.requestPermission(...)
Now please note a very important particular. Theoretically you can ask for the same permission infinitely, however from the second time you ask for the same permission the system message window will appear as following:
As you can note in this case there is a checkbox allowing the user to not be annoyed by your request anymore (Don't ask again). If the user will check it and will deny the request again any next request for the permission will be automatically denied without show any message than be careful in decide when ask for permission and, above all, to explain very clearly why you need that permission. After the second try the signal reporting the choice result will be generated again with the updated situation:
AdMobBanner
This tool allow to show AdMob banner inside QML app.
Official documentation about AdMob banner is here, please read before continue for understand the options exported by the tool. Remember for allow banner to be loaded your app need the following permissions:
android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE android.permission.WRITE_EXTERNAL_STORAGE
In add of this you have to install the AdMob required packages through Android SDK Manager. The packages you have to install are the following:
- Google Repository
- Google Play services
- Support Repository
Than you have to add the following dependencies into your app gradle file:
dependencies {
....
implementation 'com.google.android.gms:play-services-ads:16.+'
}
Banner is showed inside the following QML item:
import QtAndroidTools 1.0
QtAndroidAdMobBanner {
id: banner
unitId: "admob-banner-unit-id"
type: QtAndroidAdMobBanner.TYPE_BANNER
}
The unitId is the string generated when you create a new ad unit inside the AdMob site. It's used to identify the ad connected to your app. Using this id you can know how much you earn from this ad unit. The property type is the banner type you want to show. Possible values are:
TYPE_BANNER TYPE_FULL_BANNER TYPE_LARGE_BANNER TYPE_MEDIUM_RECTANGLE TYPE_SMART_BANNER TYPE_WIDE_SKYSCRAPER
This item generate the following signals informing regarding the ad status:
onLoadError onLoading onLoaded onClosed onClicked
The only signal passing a param is onLoadError, called in case of problem in loading ad. The param is errorId and possible values are:
ERROR_INTERNAL ERROR_NETWORK ERROR_INVALID_REQUEST ERROR_NO_FILL
When you want to load and show the banner you have to call the show() function and for hide the hide() functions as follow (banner is the id name of the item in the example above):
banner.show() banner.hide()
Please note the banner is a native android view over the QML window, that's mean will stay over anything painted into in and you can not place nothing over the banner.
AdMobInterstitial
This tool allow to show AdMob interstitial inside QML app.
Official documentation about AdMob interstitial is here, please read before continue for understand the options exported by the tool. Remember for allow interstitial to be loaded your app need the following permissions:
android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE android.permission.WRITE_EXTERNAL_STORAGE
In add of this you have to install the AdMob required packages through Android SDK Manager. The packages you have to install are the following:
- Google Repository
- Google Play services
- Support Repository
Than you have to add the following dependencies into your app gradle file:
dependencies {
....
implementation 'com.google.android.gms:play-services-ads:16.+'
}
Interstitial ad show on full screen but you have to define the AdMob unitId using the item as follow:
QtAndroidAdMobInterstitial {
id: interstitial
unitId: "admob-interstitial-unit-id"
}
The unitId is the string generated when you create a new ad unit inside the AdMob site. It's used to identify the ad connected to your app. Using this id you can know how much you earn from this ad unit.
This item generate the following signals informing regarding the ad status:
onLoadError onLoading onLoaded onClosed onClicked
The only signal passing a param is onLoadError, called in case of problem in loading ad. The param is errorId and possible values are:
ERROR_INTERNAL ERROR_NETWORK ERROR_INVALID_REQUEST ERROR_NO_FILL
Item have two function as follow:
interstitial.load() interstitial.show()
The interstitial have to be loaded before show and since loading is not immediate you have to preload a bit in advance before the time to show. You can follow the loading status through the item signals. Once revecied the onLoaded signal this mean your new interstitial is ready to be showed.
This type of ad have a button allowing the user to close it than you just have to wait about the user choice. Relember also in this case the ad window will go over the QML window and you can not paint anithing on top of it.
ApkInfo
This tool will return info about the apk containing the executed app.
The info regarding the app apk can be read directly from the QtAndroidApkInfo item as follow:
import QtAndroidTools 1.0 QtAndroidApkInfo.firstInstallTime QtAndroidApkInfo.lastUpdateTime QtAndroidApkInfo.packageName QtAndroidApkInfo.versionCode QtAndroidApkInfo.versionName QtAndroidApkInfo.requestedPermissions
Explanation about fields above can be found in the official Android documentation here. The tool export only the most important info but if you need to have some additional data you can easily add you code by using JNI interface as showed in the sources.
BatteryState
This allow monitoring the battery level and state.
This tool install a listener for monitor the battery level and on charge state. There is nothing difficult in use since there are only two properties as follow:
import QtAndroidTools 1.0 QtAndroidBatteryState.level QtAndroidBatteryState.onCharge
Both properties support QML value binding than you can assign to a control for show always the updated value as in the demo example.
SignalStrength
This tool allow to monitoring the strength of the phone signal.
This tool install a listener for monitor the phone signal. Remember for allow the library to work in this case the app need to have the following permission:
android.permission.READ_PHONE_STATE
There are two properties reporting the strength of the phone signal in row number and based to the conventional states as follow:
import QtAndroidTools 1.0 QtAndroidSignalStrength.signalStrength QtAndroidSignalStrength.signalLevel
Signal level possible states are the following:
- LEVEL_GREAT
- LEVEL_GOOD
- LEVEL_MODERATE
- LEVEL_POOR
- LEVEL_NONE
PLEASE NOTE: the report the the signal strength change doesn't arrive immediately but, instead, require some seconds to be updated after the change. Don't worry if you don't see an immediate update, just wait a little.