winzik/docs/android-native.md
David Nurdin 6ff2f954e4 Android : mise à jour automatique de l'appli comme sur PC (session PackageInstaller, redémarrage tout seul)
- moteur : AndroidApp::installSilently() / canInstallSilently() / installState() / network() / screenOn() /
  updatedJustNow() ; GameActivity + SelfUpdater : session PackageInstaller avec USER_ACTION_NOT_REQUIRED
  (UPDATE_PACKAGES_WITHOUT_USER_ACTION), statut de session, UpdateReceiver (MY_PACKAGE_REPLACED) et notification
  plein écran pour rouvrir l'appli (Android 10+ bloque le démarrage depuis l'arrière-plan)
- WinZik : avec « Mettre WinZik à jour tout seul », l'APK est téléchargé en Wi-Fi, vérifié (signature de
  update.json + SHA-256), installé à la pause ou au début d'un morceau écran éteint, après sauvegarde du morceau et
  de la position ; le bouton « Mettre à jour » passe par la même session
- correctif : fwrite(STDERR) plantait l'appli Android (pas de STDERR en PHP embarqué) à la moindre erreur de mise à jour
- essayé sur l'émulateur Android 14 (901 -> 902 -> 903 -> 904), documenté dans docs/android-native.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JkYTqrBXzYFUXiSrqYBdP3
2026-11-20 14:37:50 +01:00

196 lines
15 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# The game as a native Android app
`bin/jumphp android <game>` makes a **real Android app** of a game: no browser, no WebView. PHP 8.5, SDL2,
OpenGL ES and OpenAL run inside the app, as on the desktop; the on-screen controls (d-pad or joystick, A / B /
START) are drawn by the engine. Phones (arm64-v8a) and emulators / Chromebooks (x86_64), Android 8.0 or newer.
**A desktop app** (`ui: webview`, [tauri.md](tauri.md)): the same command makes an app of its browser build (`bin/jumphp
build`, done by the command) shown by Android's WebView from `https://appassets.androidplatform.net/` (inside the app,
no network), with a bridge for the system's save dialog, notifications, links, sharing and the clipboard
(`tools/android/webview`); no NDK, a few minutes. Output: `dist/android-native/<app>-<version>.apk` / `.aab`, the same
package, key and Google Play steps as a game. Tried in an emulator with `games/hello-desktop`.
(The other way, `bin/jumphp twa`, puts the game's web page in Chrome: [docs/android.md](android.md). With the
same package and key, the native app replaces the TWA on Google Play as a new version.)
## One command
```
bin/jumphp android pong
```
1. the first time it asks the app's **package** (`io.github.<you>.<game>`: it never changes on Google Play; the
TWA's if the game has one) and makes the **upload key** in `~/.jumphp/android/keys/<package>.keystore` (+ `.env`,
its password). Back them up; they are never in git (the TWA's key if there is one);
2. it puts the workflow `.github/workflows/android.yml` in the project and, **after your yes**, sends the key to
the repository's secrets (`ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_PASSWORD`);
3. it writes the version in `games/<game>/android/app.json` (in git: package, versionCode + 1, versionName), commits
it and, **after your yes**, pushes;
4. GitHub builds the app (first time ~25 min, then ~8: PHP and the libraries are kept in the Actions cache), and
publishes the release `android-<game>-<version>-<code>` with the **`.apk`** (a phone) and the **`.aab`**
(Google Play), signed with your key; the command downloads them into `games/<game>/dist/android-native/`.
Options: `--package`, `--version-name 1.1` (the version code goes up by one at each build), `--local` (built on this
computer in Docker: the Android SDK and its NDK in `~/.jumphp/android-sdk`, installed after your yes to Google's
license by `bin/jumphp twa`).
On a phone: `adb install games/<game>/dist/android-native/<game>-1.0.apk` (or send the .apk to the phone and open it,
"install unknown apps" allowed).
## What is in the app
| Part | Where |
|---|---|
| PHP 8.5 (embed SAPI, static) with php-sdl, sdl_image, sdl_mixer, sdl_ttf, PHP-OpenGL, PHP-OpenAL, gd (PNG), bcmath, openssl, mbstring, phar, sockets, zlib | cross-built with the NDK: `tools/android/build.sh`, the extensions' `tools/android/ext/*.m4` |
| SDL2 (its Java activity, OpenGL ES, touch, sound), SDL2_image / _mixer / _ttf, OpenAL Soft (OpenSL ES) | SDL's Android project, `tools/android/project` (Gradle, CMake) |
| `libmain.so`: unpacks the game on its first launch (each new version once, from the APK into the private storage), runs it | `tools/android/project/app/jni/src/main.c` |
| the game: `assets/game.tar` (as `export:standalone` packs it: `tools/stage-game.sh`) | |
| name, icon (the PWA's: `assets/icon.png`), orientation (the game's shape) | project.yaml |
**A music player, a radio, a podcast app** (project.yaml):
```yaml
android:
background_audio: true # plays on in the background and with the screen off
orientation: portrait # portrait | landscape | any (default: the game's shape); kept whatever the window's shape
read_audio: true # the phone's music files (Music, Download, the SD card)
ffmpeg: true # the ffmpeg program in the app: getenv('JUMPHP_FFMPEG') (below)
self_update: true # installs a newer .apk it downloaded: AndroidApp::install() (below)
mute_when_hidden: false # the engine's own rule: no sound while hidden, by default
```
The app then keeps its loop and its sound running when it goes to the background (SDL's hints
`SDL_ANDROID_BLOCK_ON_PAUSE` and `..._PAUSEAUDIO` off) and starts a **foreground service** (`PlaybackService`: a
notification "playing", a tap brings the app back, a partial wake lock for the screen off). The manifest gets the
permissions `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MEDIA_PLAYBACK`, `POST_NOTIFICATIONS` (asked at the first start
on Android 13+), `WAKE_LOCK`, and the category `audio`. PHP sees `JUMPHP_BACKGROUND_AUDIO=1`. On Google Play, declare
the foreground service (Policy > App content > Foreground service permissions: "Media playback").
`read_audio: true` adds `READ_MEDIA_AUDIO` (Android 13+) and `READ_EXTERNAL_STORAGE` (up to Android 12), asked at the
first start with the notifications in one request: PHP then lists and reads the audio files of
`/storage/emulated/0/Music`, `Download`... with plain file functions (scandir, fopen). Refused: those folders look empty.
**ffmpeg in the app** (project.yaml `android: {ffmpeg: true}`): the `ffmpeg` program (FFmpeg 8.0, LGPL build, with
LAME for MP3) is cross-built with the NDK for each ABI (`build_ffmpeg` in `tools/android/build.sh`, kept in
`~/.jumphp/android-native/ffmpeg/`, ~5 min per ABI the first time) and packed as `lib/<abi>/libffmpeg.so`. Android only
runs programs from the app's `nativeLibraryDir` (W^X since Android 10), so the APK keeps its native libraries
compressed and the install unpacks them there (`useLegacyPackaging`); `GameActivity` gives PHP the path in
**`JUMPHP_FFMPEG`** (`<nativeLibraryDir>/libffmpeg.so`, unset without the option). PHP runs it as any program:
```php
$ffmpeg = getenv('JUMPHP_FFMPEG') ?: 'ffmpeg'; // the phone's, else the computer's
$p = proc_open([$ffmpeg, '-y', '-v', 'error', '-i', $in, '-c:a', 'libmp3lame', '-b:a', '192k', $out], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
```
Inside: every decoder, demuxer, parser and filter of FFmpeg (MP3, AAC, Opus, Vorbis, FLAC, H.264, HEVC, VP8 / VP9,
MP4 / MOV, WebM / Matroska, Ogg...; `lavfi` sources), the encoders `libmp3lame aac flac alac opus vorbis pcm_* mjpeg
png`, the muxers `mp3 mp4 ipod mov matroska webm ogg opus wav flac adts image2 null segment`, the protocols `file
pipe concat data` (no network: download with PHP, convert the file). No `ffprobe` (`ffmpeg -i` tells the same on
stderr). Give arguments as an array (no shell). PHP has `proc_open`, `proc_*`, `shell_exec` (Android's `/bin/sh`)
and `posix` (`posix_kill`...). Adds ~10 MB per ABI to the APK.
**Links and the clipboard**: `JumPHP\Native\Shell::openUrl('https://...')` opens the phone's browser (SDL_OpenURL:
an `ACTION_VIEW` intent; http(s), mailto), e.g. a sign-in page whose answer comes back to a local server or a
pasted code. `Clipboard::copy()` / `paste()` (and so the `textbox` widget's copy / paste) use Android's clipboard.
They are functions JumPHP adds to php-sdl in the Android build (`docker/ext/php-sdl-system.patch`: `SDL_OpenURL`,
`SDL_SetClipboardText`, `SDL_GetClipboardText`, `SDL_HasClipboardText`); `Native::name()` is `sdl`,
`Native::supports()` says `openUrl` and `clipboard` (not `openPath` / `reveal`: no file manager to show a file in).
The soft keyboard comes with `SDL_StartTextInput()` (a focused `textbox` does it).
**An app that updates itself** (project.yaml `android: {self_update: true}`, outside Google Play: an `.apk` given
from a site or a release). PHP downloads the newer `.apk` (same package, same signing key, a higher versionCode) into
the app's storage (`JUMPHP_VAR`, `sys_get_temp_dir()`: under the app's files or cache folder), then:
```php
use JumPHP\Native\AndroidApp;
AndroidApp::versionCode(); // the installed versionCode (env JUMPHP_ANDROID_VERSION_CODE), null elsewhere
AndroidApp::versionName(); // its versionName (JUMPHP_ANDROID_VERSION_NAME); package(): JUMPHP_ANDROID_PACKAGE
AndroidApp::supportsInstall(); // the Android app built with self_update
AndroidApp::canInstall(); // "install unknown apps" already allowed for it (JUMPHP_ANDROID_CAN_INSTALL)
AndroidApp::install($apk); // the system's "update this app?" screen; true when handed over
```
`install()` is `SDL_OpenURL('file://<path>.apk')`, which `GameActivity` catches: the file goes to the package installer
as `content://<package>.apk/...` (`ApkProvider`, a read-only provider of the app's files / cache folders, like
AndroidX's FileProvider without the dependency) with `ACTION_VIEW` + `FLAG_GRANT_READ_URI_PERMISSION`. When installs
from this app are not allowed yet, Android's settings page "install unknown apps" for it opens first
(`ACTION_MANAGE_UNKNOWN_APP_SOURCES`, `package:<package>`); back in the app, allowed, the install goes on by itself.
The user confirms the update; Android then stops the app and installs the new version (its data kept). The manifest
gets `REQUEST_INSTALL_PACKAGES` (Google Play refuses it for most apps: leave `self_update` off in a Play build).
**Without the user, as on a computer** (download, check, install, restart by itself):
```php
AndroidApp::canInstallSilently(); // Android 12+, "install unknown apps" allowed, no other store owning the updates
AndroidApp::installSilently($apk); // AndroidApp::STARTED | UNSUPPORTED | MISSING
AndroidApp::installState(); // ['state' => '' | installing | confirm | failed | success, 'message', 'status']
AndroidApp::network(); // 'unmetered' (Wi-Fi) | 'metered' | 'none' | null: download big files on Wi-Fi only
AndroidApp::screenOn(); // true | false | null: install while it is off (below)
AndroidApp::updatedJustNow(); // this start follows an update the app installed itself
```
`installSilently()` is `SDL_OpenURL('file://<path>.apk?session=1')`: `GameActivity` gives the file to a **PackageInstaller
session** (`SelfUpdater`, not `ACTION_VIEW`) with `setRequireUserAction(USER_ACTION_NOT_REQUIRED)`,
`setInstallReason(INSTALL_REASON_USER)`, `setPackageSource(PACKAGE_SOURCE_OTHER)` and the manifest's
`UPDATE_PACKAGES_WITHOUT_USER_ACTION`. What Android allows, honestly (tried on an Android 14 emulator):
- **one question, once**: "install unknown apps" for the app (its settings page opens by itself, as with `install()`;
`installState()` `confirm` meanwhile). After that, **no install screen at all**, the first update included (an app
updating itself; even when adb had installed it), and the app is from then on its own installer of record. Android
8-11, or another store owning the updates (Android 14 update ownership, e.g. installed by Google Play): Android's
confirmation (`STATUS_PENDING_USER_ACTION`, `GameActivity` shows it, `confirm`);
- Android **stops the app** to replace it (no way around it). The status `PendingIntent` of the session (an activity)
and `UpdateReceiver` (`ACTION_MY_PACKAGE_REPLACED`) try to start it again, but Android 10+ blocks a start from the
background (`BAL_BLOCK` in logcat, even right after the app was on screen). What works is a **notification with a
full-screen intent** (`USE_FULL_SCREEN_INTENT`): **screen off**, Android opens the app at once by itself (it turns
the screen on once, over the lock screen: SDL starts the program only in a resumed activity), then the screen goes
off as usual and the app runs on; **screen on**, it is a heads-up notification "<app> mis à jour — toucher pour
rouvrir" to tap. So install while the screen is off (`screenOn()`), or when nothing would be lost;
- the files `GameActivity` writes for PHP are in `<files>/jumphp-android/` (`JUMPHP_ANDROID_STATE`): `install.json`,
`network`, `screen`, `relaunch` (the next start is the updated one: `JUMPHP_ANDROID_UPDATED=1`).
The app saves what it needs before calling `installSilently()` (the process is killed). WinZik
(`apps/winzik/src/Core/AutoUpdate.php`, `WinZik::goodMomentToUpdate()`): with "Mettre WinZik à jour tout seul", the APK
of the signed update.json is downloaded on Wi-Fi only, its size and SHA-256 checked, then installed when nothing plays,
or at the start of a song with the screen off (never in the middle of a song), the song and its position saved just
before; the new version opens by itself and plays on. The button "Mettre à jour" does it at once.
The saves and options are in the app's private storage (`JUMPHP_VAR`), kept across updates. PHP's output and errors
go to logcat: `adb logcat -s JumPHP`. Android's back button is Escape.
The engine knows it is on a phone: `JUMPHP_MOBILE` (Platform::isMobile()), `JUMPHP_ANDROID`, and the on-screen
controls are on (`JUMPHP_TOUCH_CONTROLS`; project.yaml `touch:` as in the browser: `pad: stick`, `a`, `b`, `start`,
`select`, `labels`). On the desktop, `JUMPHP_TOUCH_CONTROLS=1 bin/jumphp run <game>` shows them (with the mouse).
HTTPS (`$engine->http()`, online play over `wss://`): PHP's openssl (OpenSSL 3, built with the NDK) with the game's CA
certificates (`cacert.pem`, put in by `tools/stage-game.sh`; `openssl.cafile` set by main.c).
## On Google Play
In short below; the whole procedure (keys, phone checks, every Play Console declaration, review, pitfalls) is in
[google-play.md](google-play.md).
1. **A developer account**: [play.google.com/console](https://play.google.com/console) (25 $ once, an identity
check; a new personal account must have 12 testers for 14 days before going public).
2. **Create the app**: name, default language, "Game", free; the declarations (privacy policy: a page saying the
game collects nothing, e.g. on the game's site; content rating questionnaire; target audience; ads: none).
3. **Play App Signing**: Google keeps the key that signs the app for the phones; your key only proves the uploads are
yours (if you lose it, Google can reset it: Setup > App signing).
4. **The first upload by hand**: Test and release > Testing > Internal testing > Create a new release > upload the
`.aab` (`games/<game>/dist/android-native/`, or the GitHub release) > Save > Review > Start rollout. Add testers
(their Google accounts); they install from the link Google gives.
5. **The store listing**: short and full description, the icon 512 × 512 (`dist/web/icon-512.png` of
`bin/jumphp build`), a feature graphic 1024 × 500, at least 2 screenshots (`bin/jumphp shot <game>`, or on a phone).
6. **Production**: when the tests are done, promote the release (Production > Create a new release, or "Promote
release"). Google reviews it (a few hours to a few days).
7. **The next versions**: `bin/jumphp android <game> --version-name 1.1` (the version code goes up by one; Google
Play refuses a code it already has), then upload the new `.aab` the same way.
## Build it elsewhere
The workflow is plain GitHub Actions on the repository (`ubuntu-latest`, its Android SDK; the NDK r29 installed by
`sdkmanager`): Actions > android > Run workflow (game, package, version code, version name) works without the
command. The build itself, anywhere with Docker: `docker build -t jumphp/android-native docker/android-native`,
then `tools/android/build.sh` in it with `/workspace` (the project), `/cache`, `/opt/android-sdk` (with the NDK) and
`GAME`, `PACKAGE`, `VERSION_CODE`, `VERSION_NAME`, `KEYSTORE` + `KEYSTORE_PASSWORD` + `KEY_ALIAS` + `KEY_PASSWORD`.