Building code for Android with Meson has long been possible, but a bit hacky and not particularly well documented. Recently some new features have landed in Meson main, which make the experience quite a bit nicer. To demonstrate, I have updated the Platypus sample project to build and run on Android. The project itself aims demonstrate how you'd build a GUI application with shared native code on multiple platforms using native widget toolkits on each of them. Currently it supports GTK, Win32, Cocoa, WASM and Android. In addition to building the code it also generates native packages and installers.
It would be nice if you could build full Android applications with just a toolchain directly from the command line. As you start looking into how Android builds work you realize that this is not really the way to go if you want to preserve your sanity. Google has tied app building very tightly into Android Studio. Thus the simple way is to build the native code with Meson, Java/Kotlin code with Android Studio and then merge the two together.
The Platypus repo has a script called build_android.py, which does exactly this. The steps needed to get a working build are the following:
- Use Meson's env2mfile to introspect the current Android Studio installation and create cross files for all discovered Android toolchains
- Set up a build directory for the toolchain version/ABI/CPU combination given, defaulting to the newest toolchain and arm64-v8a
- Compile the code.
- Install the generated shared library in the source tree under <app source dir>/jniLibs/<cpu>.
- Android Studio will then automatically install the built libs when deploying the project.
Here is a picture of the end result. The same application is running both in an emulator (x86_64) and a physical device (arm64-v8a).
The main downside is that you have to run the native build step by hand. It should be possible to make this a custom build step in Gradle but I've never actually written Gradle code so I don't know how to do it.