Add Android companion beacon app (v1)
Kotlin/Compose foreground service advertising a connectable legacy advertisement at ~1 Hz with a counter that rotates in ServiceData every 10s: changed payload values make BlueZ emit PropertiesChanged even when the RSSI repeats, keeping the daemon's freshness clock fed for a stationary phone. Running from a foreground service with a battery optimization exemption defeats the advertising pauses that caused the false locks. Replaces third-party beacon apps; the daemon needs no changes. Verified with a real Gradle build (AGP 8.13.2, Kotlin 2.3.21, compileSdk 36).
This commit is contained in:
1 parent
aef8e2af17
commit
44510411fc
19 files changed
+917
No files matched your search
@@ -0,0 +1,48 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "org.netz.btleproximity"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "org.netz.btleproximity"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = JvmTarget.JVM_17
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("androidx.compose:compose-bom:2026.06.01"))
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Advertising needs BLUETOOTH_ADVERTISE on API 31+; the legacy
|
||||
permissions cover API 26-30. Scanning/connecting are not used. -->
|
||||
<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.BLUETOOTH_ADVERTISE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.bluetooth_le"
|
||||
android:required="true" />
|
||||
|
||||
<application
|
||||
android:label="@string/app_name"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".BeaconService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="connectedDevice" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,206 @@
|
||||
package org.netz.btleproximity
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.le.AdvertiseData
|
||||
import android.bluetooth.le.AdvertisingSet
|
||||
import android.bluetooth.le.AdvertisingSetCallback
|
||||
import android.bluetooth.le.AdvertisingSetParameters
|
||||
import android.bluetooth.le.BluetoothLeAdvertiser
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.ParcelUuid
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import java.util.UUID
|
||||
import kotlin.random.Random
|
||||
|
||||
data class BeaconUiState(
|
||||
val running: Boolean = false,
|
||||
val message: String = "beacon is off",
|
||||
)
|
||||
|
||||
/**
|
||||
* Foreground service that advertises a connectable legacy BLE advertisement
|
||||
* at ~1 Hz. The ServiceData payload carries a counter that is rotated every
|
||||
* ROTATE_INTERVAL_MS via AdvertisingSet.setAdvertisingData — a changed
|
||||
* payload makes BlueZ emit PropertiesChanged even when the RSSI value
|
||||
* repeats, which is what keeps the desktop daemon's freshness clock fed
|
||||
* while the phone sits still.
|
||||
*/
|
||||
class BeaconService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var advertiser: BluetoothLeAdvertiser? = null
|
||||
private var advertisingSet: AdvertisingSet? = null
|
||||
private var counter = Random.nextLong()
|
||||
private var failed = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_STOP -> stopSelf()
|
||||
else -> startBeacon()
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private fun startBeacon() {
|
||||
failed = false
|
||||
updateStatus(BeaconUiState(running = true, message = getString(R.string.status_starting)))
|
||||
startFg(buildNotification(getString(R.string.notif_starting)))
|
||||
|
||||
val adapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
|
||||
if (adapter?.isEnabled != true) {
|
||||
fail(getString(R.string.status_bt_off))
|
||||
return
|
||||
}
|
||||
val adv = adapter.bluetoothLeAdvertiser
|
||||
if (adv == null) {
|
||||
fail(getString(R.string.status_unsupported))
|
||||
return
|
||||
}
|
||||
advertiser = adv
|
||||
|
||||
val params = AdvertisingSetParameters.Builder()
|
||||
.setLegacyMode(true)
|
||||
// The desktop's pre-lock connect probe needs a connectable
|
||||
// advertisement to attach to.
|
||||
.setConnectable(true)
|
||||
.setScannable(true)
|
||||
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
|
||||
.setInterval(AdvertisingSetParameters.INTERVAL_HIGH) // ~1 Hz
|
||||
.build()
|
||||
|
||||
try {
|
||||
adv.startAdvertisingSet(params, advertiseData(), null, null, null, callback)
|
||||
} catch (e: SecurityException) {
|
||||
fail(getString(R.string.status_permission, e.message ?: ""))
|
||||
}
|
||||
}
|
||||
|
||||
private val callback = object : AdvertisingSetCallback() {
|
||||
override fun onAdvertisingSetStarted(set: AdvertisingSet?, txPower: Int, status: Int) {
|
||||
if (status != AdvertisingSetCallback.ADVERTISE_SUCCESS || set == null) {
|
||||
fail(getString(R.string.status_failed, status))
|
||||
return
|
||||
}
|
||||
advertisingSet = set
|
||||
updateNotification(getString(R.string.notif_running))
|
||||
updateStatus(BeaconUiState(running = true, message = getString(R.string.status_running)))
|
||||
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
delay(ROTATE_INTERVAL_MS)
|
||||
val current = advertisingSet ?: break
|
||||
counter++
|
||||
try {
|
||||
current.setAdvertisingData(advertiseData())
|
||||
} catch (e: Exception) {
|
||||
updateStatus(
|
||||
BeaconUiState(running = true, message = getString(R.string.status_rotate, e.message ?: ""))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun advertiseData(): AdvertiseData =
|
||||
AdvertiseData.Builder()
|
||||
.addServiceData(SERVICE_UUID, counterBytes())
|
||||
.setIncludeDeviceName(false)
|
||||
.setIncludeTxPowerLevel(false)
|
||||
.build()
|
||||
|
||||
private fun counterBytes(): ByteArray {
|
||||
val bytes = ByteArray(8)
|
||||
for (i in 0 until 8) bytes[i] = (counter ushr (8 * i)).toByte()
|
||||
return bytes
|
||||
}
|
||||
|
||||
private fun fail(message: String) {
|
||||
failed = true
|
||||
updateStatus(BeaconUiState(running = false, message = message))
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun startFg(notification: Notification) {
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
|
||||
)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(text: String): Notification {
|
||||
val nm = getSystemService(NotificationManager::class.java)
|
||||
nm.createNotificationChannel(
|
||||
NotificationChannel(CHANNEL_ID, getString(R.string.notif_channel_name), NotificationManager.IMPORTANCE_LOW)
|
||||
)
|
||||
return Notification.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_beacon)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(text)
|
||||
.setContentIntent(
|
||||
PendingIntent.getActivity(
|
||||
this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun updateNotification(text: String) {
|
||||
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, buildNotification(text))
|
||||
}
|
||||
|
||||
private fun updateStatus(state: BeaconUiState) {
|
||||
uiState.value = state
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
try {
|
||||
advertiser?.stopAdvertisingSet(callback)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
advertisingSet = null
|
||||
if (!failed) {
|
||||
uiState.value = BeaconUiState(running = false, message = getString(R.string.status_stopped))
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
// Unassigned 16-bit UUID; the desktop daemon does not filter on it
|
||||
// (it matches the bonded MAC), it only needs the value to change.
|
||||
val SERVICE_UUID: ParcelUuid =
|
||||
ParcelUuid(UUID.fromString("0000fca7-0000-1000-8000-00805f9b34fb"))
|
||||
|
||||
const val ACTION_STOP = "org.netz.btleproximity.action.STOP"
|
||||
const val CHANNEL_ID = "beacon"
|
||||
const val NOTIFICATION_ID = 1
|
||||
const val ROTATE_INTERVAL_MS = 10_000L
|
||||
|
||||
val uiState = MutableStateFlow(BeaconUiState())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package org.netz.btleproximity
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
MaterialTheme {
|
||||
BeaconScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BeaconScreen() {
|
||||
val context = LocalContext.current
|
||||
val state by BeaconService.uiState.collectAsState()
|
||||
var grantError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { grants ->
|
||||
if (grants.values.all { it }) {
|
||||
context.startForegroundService(Intent(context, BeaconService::class.java))
|
||||
} else {
|
||||
grantError = context.getString(R.string.status_permission_denied)
|
||||
}
|
||||
}
|
||||
|
||||
val settingsLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { }
|
||||
|
||||
fun requestPermissionsAndStart() {
|
||||
val wanted = buildList {
|
||||
if (Build.VERSION.SDK_INT >= 31) add(Manifest.permission.BLUETOOTH_ADVERTISE)
|
||||
if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
if (wanted.isEmpty()) {
|
||||
context.startForegroundService(Intent(context, BeaconService::class.java))
|
||||
} else {
|
||||
permissionLauncher.launch(wanted.toTypedArray())
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(state.message, style = MaterialTheme.typography.bodyLarge)
|
||||
|
||||
if (state.running) {
|
||||
Button(
|
||||
onClick = {
|
||||
context.startService(
|
||||
Intent(context, BeaconService::class.java).setAction(BeaconService.ACTION_STOP)
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.btn_stop))
|
||||
}
|
||||
} else {
|
||||
Button(onClick = { requestPermissionsAndStart() }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.btn_start))
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
Text(stringResource(R.string.expl_payload), style = MaterialTheme.typography.bodySmall)
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
if (!pm.isIgnoringBatteryOptimizations(context.packageName)) {
|
||||
val direct = Intent(
|
||||
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
)
|
||||
try {
|
||||
settingsLauncher.launch(direct)
|
||||
} catch (_: Exception) {
|
||||
settingsLauncher.launch(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.btn_battery))
|
||||
}
|
||||
|
||||
grantError?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:pathData="M46,28 L62,42 L46,56 M46,52 L62,66 L46,80"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeWidth="5"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:fillColor="#00000000" />
|
||||
</vector>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M10,4 L16,10 L10,16 M10,14 L16,20 L10,26"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeWidth="2"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:fillColor="#00000000" />
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#0B57D0</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,19 @@
|
||||
<resources>
|
||||
<string name="app_name">Proximity Beacon</string>
|
||||
<string name="btn_start">Start beacon</string>
|
||||
<string name="btn_stop">Stop beacon</string>
|
||||
<string name="btn_battery">Exempt from battery optimization</string>
|
||||
<string name="status_starting">Starting…</string>
|
||||
<string name="status_running">Advertising at ~1 Hz. Counter rotates every 10 s.</string>
|
||||
<string name="status_stopped">Beacon is off</string>
|
||||
<string name="status_bt_off">Bluetooth is off — enable it and try again</string>
|
||||
<string name="status_unsupported">This phone does not support BLE advertising</string>
|
||||
<string name="status_failed">Advertising failed (status %1$d)</string>
|
||||
<string name="status_permission">Missing permission: %1$s</string>
|
||||
<string name="status_permission_denied">Advertising permission was denied — the beacon cannot run</string>
|
||||
<string name="status_rotate">Counter rotation failed: %1$s</string>
|
||||
<string name="notif_channel_name">Beacon status</string>
|
||||
<string name="notif_starting">Starting BLE advertising…</string>
|
||||
<string name="notif_running">Advertising for the desktop proximity daemon</string>
|
||||
<string name="expl_payload">The beacon rotates its advertised counter every 10 s so the desktop daemon always sees fresh evidence, even when the phone sits perfectly still.</string>
|
||||
</resources>
|
||||
Reference in new issue
Block a user