Add a standard reply fallback to wireless pairing (#3811)

* Add a standard reply fallback to wireless pairing

* Keep pairing retry guidance visible in the status notification

* Show pairing results when the keypad channel is disabled

* Keep Cancel available on the pairing reply notification
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-12-06 14:40:33 -05:00
1 parent 6d925af599
commit 9ca810d220
4 files changed
+82 -11

No files matched your search

@@ -4,6 +4,7 @@ import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.RemoteInput
import android.app.Service
import android.content.Context
import android.content.Intent
@@ -14,6 +15,7 @@ import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.util.TypedValue
import android.widget.RemoteViews
import com.droiddeck.launcher.FrontEndActivity
@@ -45,7 +47,10 @@ class WirelessAdbPairingService : Service() {
@Volatile private var working = false
@Volatile private var limitEnabled = false
@Volatile private var session = 0
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
private val timeout = Runnable {
Log.w(TAG, "Pairing timed out in ${current.value.javaClass.simpleName}")
finish(Stage.Failed(getString(R.string.adbpair_timed_out)))
}
override fun onBind(intent: Intent?): IBinder? = null
@@ -63,6 +68,17 @@ class WirelessAdbPairingService : Service() {
stopSelf(startId)
}
}
ACTION_REPLY -> {
if (intent.data?.host == keypadToken && current.value is Stage.CodeNeeded && pairingPort != null && !working) {
val reply = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_REPLY)
val code = WirelessPairingKeypad.parseReply(reply)
Log.i(TAG, "Standard pairing reply received; valid format=${code != null}")
if (code == null) show(Stage.CodeNeeded(getString(R.string.adbpair_six_digits)))
else onCode(code)
} else if (current.value == Stage.Idle) {
stopSelf(startId)
}
}
ACTION_CANCEL -> finish(Stage.Idle)
null -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
else -> if (discovery == null && !working) stopSelf(startId)
@@ -91,26 +107,33 @@ class WirelessAdbPairingService : Service() {
val owner = session
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
val listener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onDiscoveryStarted(serviceType: String) { Log.i(TAG, "Pairing discovery started") }
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
.onFailure { Log.w(TAG, "Could not start pairing service resolution") }
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) = Unit
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
main.post { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed_code, errorCode))) }
Log.w(TAG, "Pairing discovery start failed: $errorCode")
main.post { if (owner == session) finish(Stage.Failed(getString(R.string.adbpair_discovery_failed_code, errorCode))) }
}
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
}
runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) }
.onSuccess { nsd = manager; discovery = listener }
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
.onFailure {
Log.w(TAG, "Could not start pairing discovery")
finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString())))
}
}
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
return object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
Log.w(TAG, "Pairing service resolution failed: $errorCode")
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host ?: return
if (!WirelessAdbFix.isLocalAddress(address)) return
@@ -120,6 +143,7 @@ class WirelessAdbPairingService : Service() {
pairingHost = address.hostAddress
pairingPort = serviceInfo.port
if (endpointChanged) {
Log.i(TAG, "Local pairing service resolved; entering CodeNeeded")
resetKeypad()
show(Stage.CodeNeeded())
}
@@ -182,7 +206,12 @@ class WirelessAdbPairingService : Service() {
// A new high-priority notification can pop over Settings. Updating the
// quiet foreground-service notification can leave the keypad in the shade.
// End any previous indeterminate progress even if this is a code retry.
if (!quietUpdate) manager.notify(NOTIFICATION_ID, notification(stage, foregroundCodeEntry = true))
if (!quietUpdate) {
manager.notify(NOTIFICATION_ID, notification(stage, foregroundCodeEntry = true))
val keypadImportance = manager.getNotificationChannel(CHANNEL_ID)?.importance
val statusImportance = manager.getNotificationChannel(PROGRESS_CHANNEL_ID)?.importance
Log.i(TAG, "CodeNeeded notifications: keypad importance=$keypadImportance, status importance=$statusImportance, reply=${pairingPort != null}")
}
manager.notify(KEYPAD_NOTIFICATION_ID, notification(stage, quietUpdate))
} else {
manager.cancel(KEYPAD_NOTIFICATION_ID)
@@ -245,7 +274,10 @@ class WirelessAdbPairingService : Service() {
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
val quiet = foregroundCodeEntry || stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
val terminalStatusFallback = (stage == Stage.Done || stage is Stage.Failed) &&
manager?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
val quiet = foregroundCodeEntry || stage == Stage.Waiting || stage == Stage.Idle ||
stage is Stage.Working || terminalStatusFallback
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentIntent(open)
@@ -268,7 +300,13 @@ class WirelessAdbPairingService : Service() {
.setLocalOnly(true)
.setOngoing(true)
.setOnlyAlertOnce(foregroundCodeEntry || quietUpdate)
if (!foregroundCodeEntry) {
if (foregroundCodeEntry) {
val message = stage.error ?: getString(R.string.adbpair_title_code)
builder.setContentText(message)
if (stage.error != null) builder.setStyle(Notification.BigTextStyle().bigText(message))
if (pairingPort != null) builder.addAction(codeReplyAction())
builder.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
} else {
// Keep the keypad separate from status/install notifications. Android owns
// the heads-up timeout; the drawer remains usable without expanding a group.
builder.setGroup(KEYPAD_GROUP)
@@ -306,6 +344,21 @@ class WirelessAdbPairingService : Service() {
return builder.build()
}
private fun codeReplyAction(): Notification.Action {
// SystemUI must fill in RemoteInput results. Keep the mutable intent explicit
// and bind it to this pairing attempt, just like the keypad's intents.
val intent = Intent(this, WirelessAdbPairingService::class.java)
.setAction(ACTION_REPLY)
.setData(Uri.Builder().scheme("droiddeck-pairing").authority(keypadToken).appendPath("reply").build())
val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
val reply = PendingIntent.getService(this, 2, intent, flags)
val input = RemoteInput.Builder(KEY_REPLY).setLabel(getString(R.string.adbpair_code_label)).build()
return Notification.Action.Builder(null, getString(R.string.adbpair_reply_action), reply)
.addRemoteInput(input)
.setAllowGeneratedReplies(false)
.build()
}
private fun pairingKeypad(keyHeightDp: Int? = null): RemoteViews = RemoteViews(packageName, R.layout.wireless_pairing_keypad).apply {
val ids = intArrayOf(R.id.pair_key_0, R.id.pair_key_1, R.id.pair_key_2, R.id.pair_key_3, R.id.pair_key_4,
R.id.pair_key_5, R.id.pair_key_6, R.id.pair_key_7, R.id.pair_key_8, R.id.pair_key_9,
@@ -338,6 +391,9 @@ class WirelessAdbPairingService : Service() {
private const val KEYPAD_GROUP = "wireless-adb-keypad"
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
private const val ACTION_KEYPAD = "com.droiddeck.launcher.action.WIRELESS_ADB_KEYPAD"
private const val TAG = "WirelessAdbPairing"
private const val ACTION_REPLY = "com.droiddeck.launcher.action.WIRELESS_ADB_REPLY"
private const val KEY_REPLY = "pairing_code"
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
private const val TIMEOUT_MS = 5 * 60_000L
@@ -365,9 +421,12 @@ class WirelessAdbPairingService : Service() {
fun notificationsEnabled(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
/** Pairing needs this notification channel to show the keypad over Android Settings. */
fun channelBlocked(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
/** Either the keypad or the standard reply channel can submit a pairing code. */
fun channelBlocked(context: Context): Boolean {
val manager = context.getSystemService(NotificationManager::class.java) ?: return false
return manager.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE &&
manager.getNotificationChannel(PROGRESS_CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
}
fun channelId(): String = CHANNEL_ID
}
@@ -25,5 +25,8 @@ internal class WirelessPairingKeypad {
const val LENGTH = 6
const val DELETE = 10
const val SUBMIT = 11
fun parseReply(text: CharSequence?): String? =
text?.toString()?.trim()?.takeIf { it.length == LENGTH && it.all { digit -> digit in '0'..'9' } }
}
}
+1
View File
@@ -2649,6 +2649,7 @@
<string name="adbpair_waiting_text">Turn on Wireless debugging, then tap “Pair device with pairing code”.</string>
<string name="adbpair_waiting_long">Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification.</string>
<string name="adbpair_code_label">6-digit pairing code</string>
<string name="adbpair_reply_action">Enter code</string>
<string name="adbpair_keypad_entered">%1$d of 6 digits entered</string>
<string name="adbpair_keypad_delete">Delete last digit</string>
<string name="adbpair_title_code">Enter the Wi-Fi pairing code</string>
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -27,6 +28,13 @@ class WirelessPairingKeypadTest {
assertEquals("321986", pad.digits)
}
@Test fun standardReplyKeepsLeadingZeroesAndRejectsNonAsciiOrIncompleteCodes() {
assertEquals("001234", WirelessPairingKeypad.parseReply(" 001234 "))
listOf(null, "", "12345", "1234567", "123 45", "abcdef", "١٢٣٤٥٦").forEach {
assertNull(WirelessPairingKeypad.parseReply(it))
}
}
@Test fun startingAnotherAttemptClearsTheCode() {
val pad = WirelessPairingKeypad()
assertFalse(pad.press(-1))