0.38.0 (72): Bluetooth LE MIDI controllers in Settings (Android and iOS)

- Android: BleMidi scans for the BLE MIDI service, connects through
  MidiManager.openBluetoothDevice, remembers and reconnects controllers;
  Settings › MIDI inputs › Bluetooth MIDI (Scan / Connect / Disconnect / Forget)
- iOS: the system Bluetooth MIDI panel from Setup › MIDI Sync, connected
  controllers remembered and reconnected at launch via CoreBluetooth

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 14:57:53 +01:00
co-authored by Claude Opus 5.5
parent 2bc5cb1cbb
commit 4d9e2328cb
18 changed files with 574 additions and 7 deletions
+10 -1
View File
@@ -7,12 +7,20 @@
FOREGROUND_SERVICE : keep the sequencer alive while the app is backgrounded.
FOREGROUND_SERVICE_MEDIA_PLAYBACK : Android 14 requires a typed FGS.
POST_NOTIFICATIONS : show the media transport notification (Android 13+).
BLUETOOTH_CONNECT : Bluetooth MIDI + gamepad on Android 12+. -->
BLUETOOTH_CONNECT : Bluetooth MIDI + gamepad on Android 12+.
BLUETOOTH_SCAN : finding BLE MIDI controllers (Settings › MIDI inputs) on
Android 12+; never used to derive location.
BLUETOOTH / _ADMIN / ACCESS_FINE_LOCATION : the same scan on Android 8-11. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
<!-- Hardware we can *use* but do not *require* (so the app still installs on
devices without them). Code must always feature-detect at runtime. -->
@@ -20,6 +28,7 @@
<uses-feature android:name="android.software.midi" android:required="false" />
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<!-- Lets SongIntents.isTrustedReplace see which app owns a content provider, so
@@ -57,6 +57,8 @@ class SizzleApp : Application() {
val keyboardInput: KeyboardInput by lazy { KeyboardInput(inputRouter) }
val gamepadInput: GamepadInput by lazy { GamepadInput(inputRouter) }
val midiInput: MidiInput by lazy { MidiInput(this, inputRouter, soundModule) }
/** Bluetooth LE MIDI controllers (found, connected and remembered in Settings). */
val bleMidi: cc.tiredsysadmin.android.sizzle.input.BleMidi by lazy { cc.tiredsysadmin.android.sizzle.input.BleMidi(this) }
/** Headless MIDI → engine routing (see [MidiSoundModule]). Lives here, with the
* engine, so it keeps playing incoming notes with no Activity or ViewModel. */
@@ -141,7 +143,10 @@ class SizzleApp : Application() {
}
fun acquireMidi(owner: String) {
if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() }
if (midiOwners.add(owner) && midiOwners.size == 1) {
midiInput.start(); midiClock.start()
bleMidi.start(); bleMidi.reconnectRemembered()
}
}
/** Re-scan MIDI sources (MainActivity.onResume): opens anything enabled that
@@ -149,7 +154,7 @@ class SizzleApp : Application() {
fun refreshMidi() { if (midiOwners.isNotEmpty()) midiInput.refresh() }
fun releaseMidi(owner: String) {
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { bleMidi.closeAll(); midiInput.stop(); midiClock.stop() }
}
/**
@@ -207,6 +212,8 @@ class SizzleApp : Application() {
_soundModuleEnabled.value = s.soundModule
midiInput.restoreDisabled(s.midiSourcesOff)
midiInput.onDisabledChanged = { keys -> appScope.launch { settingsStore.saveMidiSourcesOff(keys) } }
bleMidi.restoreRemembered(s.bleMidiDevices)
bleMidi.onRememberedChanged = { devices -> appScope.launch { settingsStore.saveBleMidiDevices(devices) } }
}
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -0,0 +1,230 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.pm.PackageManager
import android.bluetooth.BluetoothDevice
import android.media.midi.MidiDevice
import android.media.midi.MidiDeviceInfo
import android.media.midi.MidiManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.ParcelUuid
import android.util.Log
import java.util.UUID
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/** A Bluetooth LE MIDI controller Sizzle found or remembers. */
data class BleMidiDevice(
val address: String,
val name: String,
val connected: Boolean,
val connecting: Boolean,
val remembered: Boolean,
)
/**
* Bluetooth LE MIDI controllers: Android lists a BLE MIDI device to MIDI apps only
* once some app has connected it, so Settings scans for the BLE MIDI service,
* shows what it finds, and connects the one the user picks
* ([MidiManager.openBluetoothDevice]). The connection is held here for as long as
* Sizzle runs; while it is, the device is an ordinary MIDI source that [MidiInput]
* picks up through its device callback (listed, switchable, played).
*
* Connected devices are remembered ([remembered], persisted by the caller via
* [onRememberedChanged]) and connected again by address at the next start
* ([reconnectRemembered]) — no scan needed. Main thread.
*/
class BleMidi(private val context: Context) {
private val handler = Handler(Looper.getMainLooper())
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
private val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
private val found = LinkedHashMap<String, String>() // address -> name, from scans and memory
private val open = HashMap<String, MidiDevice>()
private val connecting = HashSet<String>()
/** Addresses of the controllers to connect again at start ("address|name" when saved). */
var remembered: Map<String, String> = emptyMap()
private set
var onRememberedChanged: ((Map<String, String>) -> Unit)? = null
private val _devices = MutableStateFlow<List<BleMidiDevice>>(emptyList())
val devices: StateFlow<List<BleMidiDevice>> = _devices.asStateFlow()
private val _scanning = MutableStateFlow(false)
val scanning: StateFlow<Boolean> = _scanning.asStateFlow()
private val _error = MutableStateFlow<String?>(null)
/** Why the last scan or connection failed, for Settings; null when fine. */
val error: StateFlow<String?> = _error.asStateFlow()
/** This device can do BLE MIDI at all (BLE + the MIDI API). */
val supported: Boolean
get() = adapter != null && midiManager != null &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
/** Runtime permissions a scan needs (Android 12+: scan + connect; before: location). */
fun requiredPermissions(): Array<String> =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
} else {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
fun hasPermissions(): Boolean = requiredPermissions().all {
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
}
private fun canConnect(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
private var callbackRegistered = false
/** Watch for connections that drop on their own (out of range, switched off). */
fun start() {
val mm = midiManager ?: return
if (callbackRegistered) return
callbackRegistered = true
@Suppress("DEPRECATION")
mm.registerDeviceCallback(object : MidiManager.DeviceCallback() {
override fun onDeviceRemoved(device: MidiDeviceInfo) {
if (device.type != MidiDeviceInfo.TYPE_BLUETOOTH) return
@Suppress("DEPRECATION")
val bt = device.properties.getParcelable<BluetoothDevice>(MidiDeviceInfo.PROPERTY_BLUETOOTH_DEVICE)
bt?.address?.let(::deviceRemoved)
}
}, handler)
}
fun restoreRemembered(saved: Map<String, String>) {
remembered = saved
found.putAll(saved)
publish()
}
// ---------------------------------------------------------------- scanning
private val callback = object : ScanCallback() {
@SuppressLint("MissingPermission")
override fun onScanResult(callbackType: Int, result: ScanResult) {
val address = result.device.address ?: return
val name = result.scanRecord?.deviceName ?: runCatching { result.device.name }.getOrNull() ?: "BLE MIDI device"
if (found[address] != name) { found[address] = name; publish() }
}
override fun onScanFailed(errorCode: Int) {
_error.value = "Bluetooth scan failed (error $errorCode)."
_scanning.value = false
}
}
private val stopScanLater = Runnable { stopScan() }
/** Look for BLE MIDI controllers for [SCAN_MS]. Needs [hasPermissions] and Bluetooth on. */
@SuppressLint("MissingPermission")
fun startScan() {
_error.value = null
if (!supported) { _error.value = "This device has no Bluetooth LE MIDI support."; return }
if (!hasPermissions()) { _error.value = "Sizzle needs the Bluetooth permission to look for controllers."; return }
val scanner = adapter?.takeIf { it.isEnabled }?.bluetoothLeScanner
if (scanner == null) { _error.value = "Bluetooth is off. Turn it on, then scan again."; return }
if (_scanning.value) return
val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(MIDI_SERVICE)).build()
val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
runCatching { scanner.startScan(listOf(filter), settings, callback) }
.onFailure { _error.value = "Couldn't start the Bluetooth scan: ${it.message}"; return }
_scanning.value = true
handler.postDelayed(stopScanLater, SCAN_MS)
}
@SuppressLint("MissingPermission")
fun stopScan() {
handler.removeCallbacks(stopScanLater)
if (!_scanning.value) return
runCatching { adapter?.bluetoothLeScanner?.stopScan(callback) }
_scanning.value = false
}
// ---------------------------------------------------------------- connecting
/** Connect the controller at [address]; it then appears among the MIDI inputs. */
@SuppressLint("MissingPermission")
fun connect(address: String) {
val mm = midiManager ?: return
if (address in open || address in connecting) return
if (!canConnect()) { _error.value = "Sizzle needs the Bluetooth permission to connect."; return }
val device = runCatching { adapter?.getRemoteDevice(address) }.getOrNull() ?: return
stopScan() // scanning slows connecting down
connecting += address
publish()
mm.openBluetoothDevice(device, { midi ->
connecting -= address
if (midi == null) {
_error.value = "Couldn't connect to ${found[address] ?: address}. Is it on and nearby?"
} else {
_error.value = null
open[address] = midi
remember(address, found[address] ?: midi.info.properties.getString(MidiDeviceInfo.PROPERTY_NAME) ?: address)
Log.i(TAG, "${found[address]}: connected")
}
publish()
}, handler)
}
/** Disconnect the controller at [address]; [forget] also stops reconnecting it at start. */
fun disconnect(address: String, forget: Boolean) {
open.remove(address)?.let { runCatching { it.close() } }
if (forget && address in remembered) {
remembered = remembered - address
onRememberedChanged?.invoke(remembered)
}
publish()
}
/** Connect every remembered controller (at start and when Settings opens). */
fun reconnectRemembered() {
for (address in remembered.keys) if (address !in open) connect(address)
}
/** A connection dropped on its own (out of range, switched off): forget the handle. */
fun deviceRemoved(address: String) {
open.remove(address)?.let { runCatching { it.close() } }
publish()
}
/** Close every connection (Sizzle shutting down MIDI). */
fun closeAll() {
stopScan()
open.values.forEach { runCatching { it.close() } }
open.clear()
publish()
}
private fun remember(address: String, name: String) {
if (remembered[address] == name) return
remembered = remembered + (address to name)
onRememberedChanged?.invoke(remembered)
}
private fun publish() {
_devices.value = found.map { (address, name) ->
BleMidiDevice(address, name, address in open, address in connecting, address in remembered)
}.sortedWith(compareByDescending<BleMidiDevice> { it.connected }.thenBy { it.name.lowercase() })
}
companion object {
private const val TAG = "SizzleBleMidi"
/** The BLE MIDI service (Apple's / the MMA's BLE-MIDI specification). */
val MIDI_SERVICE: UUID = UUID.fromString("03B80E5A-EDE8-4B33-A751-6CE34EC4C700")
private const val SCAN_MS = 15_000L
}
}
@@ -39,6 +39,8 @@ data class AppSettings(
val soundModule: Boolean = false,
/** MIDI sources the user switched off in Setup ([cc.tiredsysadmin.android.sizzle.input.MidiSourceKey]). */
val midiSourcesOff: Set<String> = emptySet(),
/** Bluetooth LE MIDI controllers to connect at start: address -> name. */
val bleMidiDevices: Map<String, String> = emptyMap(),
)
/**
@@ -65,6 +67,10 @@ class SettingsStore(private val context: Context) {
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
soundModule = prefs[SOUND_MODULE] ?: false,
midiSourcesOff = prefs[MIDI_SOURCES_OFF] ?: emptySet(),
// "address|name" each (a BLE address never contains '|').
bleMidiDevices = (prefs[BLE_MIDI] ?: emptySet()).associate {
it.substringBefore('|') to it.substringAfter('|', it.substringBefore('|'))
},
)
}
@@ -114,6 +120,11 @@ class SettingsStore(private val context: Context) {
context.settingsDataStore.edit { prefs -> prefs[MIDI_SOURCES_OFF] = keys }
}
/** Persist the remembered Bluetooth LE MIDI controllers. */
suspend fun saveBleMidiDevices(devices: Map<String, String>) {
context.settingsDataStore.edit { prefs -> prefs[BLE_MIDI] = devices.map { (a, n) -> "$a|$n" }.toSet() }
}
private companion object {
val PALETTE = stringPreferencesKey("palette")
val RECORD_DIR = stringPreferencesKey("recordDirUri")
@@ -125,5 +136,6 @@ class SettingsStore(private val context: Context) {
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
val SOUND_MODULE = booleanPreferencesKey("soundModule")
val MIDI_SOURCES_OFF = stringSetPreferencesKey("midiSourcesOff")
val BLE_MIDI = stringSetPreferencesKey("bleMidiDevices")
}
}
@@ -160,6 +160,9 @@ class AppViewModel(
/** Close and reopen every MIDI source (e.g. after the sending app restarted). */
fun reconnectMidi() = midiInput.reconnect()
/** Bluetooth LE MIDI controllers: scan, connect, forget (Settings › MIDI inputs). */
val bleMidi: cc.tiredsysadmin.android.sizzle.input.BleMidi get() = sizzleApp.bleMidi
// ----- A song opened from another app (VIEW / SEND intent) -----
/** Waiting for the user to confirm replacing the current song, or to read why
* it can't be opened. */
@@ -574,6 +574,89 @@ private fun MidiInputsList(vm: AppViewModel) {
src.enabled,
) { vm.setMidiSourceEnabled(src.key, it) }
}
HorizontalDivider()
BluetoothMidiList(vm)
}
/**
* Bluetooth LE MIDI controllers: SCAN looks for them for 15 s (asking for the
* Bluetooth permission first), CONNECT opens one, and from then on it is one of
* the MIDI inputs above, connected again at every start until FORGET.
*/
@Composable
private fun BluetoothMidiList(vm: AppViewModel) {
val ble = vm.bleMidi
val devices by ble.devices.collectAsState()
val scanning by ble.scanning.collectAsState()
val error by ble.error.collectAsState()
val askPermission = rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions(),
) { ble.startScan() } // without the permission it reports what is missing
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Bluetooth MIDI", style = MaterialTheme.typography.bodyMedium)
Text(
if (!ble.supported) "This device has no Bluetooth LE MIDI support."
else "Find Bluetooth LE MIDI controllers and connect them. Connected ones are listed " +
"with the MIDI inputs and reconnect at every start.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (ble.supported) {
OutlinedButton(onClick = {
when {
scanning -> ble.stopScan()
ble.hasPermissions() -> ble.startScan()
else -> askPermission.launch(ble.requiredPermissions())
}
}) { Text(if (scanning) "Stop" else "Scan") }
}
}
if (scanning) {
Text(
"Scanning… switch the controller on (or into pairing mode) nearby.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
error?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
}
for (d in devices) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(d.name, style = MaterialTheme.typography.bodyMedium)
Text(
when {
d.connecting -> "Connecting…"
d.connected -> "Connected"
d.remembered -> "Remembered — not connected"
else -> "Found"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
when {
d.connecting -> {}
d.connected -> OutlinedButton(onClick = { ble.disconnect(d.address, forget = false) }) { Text("Disconnect") }
else -> OutlinedButton(onClick = { ble.connect(d.address) }) { Text("Connect") }
}
if (d.remembered) {
TextButton(onClick = { ble.disconnect(d.address, forget = true) }) { Text("Forget") }
}
}
}
}
/** A labelled switch row (title + supporting text + trailing Switch). */