Friday, May 1, 2020

Qt & Android: Setting wallpaper

Is your Android app written using Qt? Would you like to change the wallpaper on your Android device programmatically? Then join me in creating an Android app that generates and saves the image as wallpaper.

Using Qt Creator, create a new 'Qt Quick Application - Empty' naming it WallpaperExample.


Select both Desktop and Android Kits.  It is usually convenient to have a Desktop app to test non-Android features of the app.


Next, verify the WallpaperExample Desktop builds and runs.


Update main.qml so that it can used to set the wallpaper.


Create the AndroidManifest.xml. Additional changes to the XML will be neccessary later.
Select all the Android supported ABI's.


Now, verify the WallpaperExample Android builds and runs.


An effective  approach  for a Qt/QML/C++ app to perform Android specific tasks is to use Android's Java API. Android Java classes are accessible to a Qt application using the JNI convenience APIs in the Qt Android Extras module, such as QAndroidJniObject::callStaticObjectMethod.


Java classes in a Qt Android project need to maintain the Java naming conventions and the directory package structure.
The package name is the same package name assigned in the Android-Mainfest.xml.
Because this Java class, WallpaperGenerator,  requires access to application-specific resources, the Android Context must be passed in from QAndroidJniObject::callStaticMethod call in the Qt class.


The QAndroidJniObject::callStaticMethod calls the static method WallpaperGenerator.generateWallpaper which generates and sets the Android wallpaper on a seperate thread to prevent UI delay.










The method WallpaperGenerator.getWallpaper calls an image generating service and reads the response using common Java API. 
The method WallpaperGenerator.setWallpaper creates and sets the bitmap image using Android  specific API. 
An alternative to calling the methods getWallpaper and setWallpaper, the method generateWallpaper can be called.













AndroidManifest.xml requires a few changes before the app can run. Android requires the manifest.permission.SET_WALLPAPER permission. Starting with Android 9, API level 28, cleartext support is disabled by default and this app communicates with the wallpaper generating server using http, so usesCleartextTraffic must be enabled.


That's all it takes. Run the app and set wallpaper.


























No comments:

Post a Comment

Qt & Android: Setting wallpaper

Is your Android app written using Qt? Would you like to change the wallpaper on your Android device programmatically? Then join me in creati...