Merge pull request #1007 from permissionlesstech/fix/mesh-service-lifecycle

Fix foreground-service retries and Wi-Fi Aware recovery
This commit is contained in:
callebtc authored and GitHub committed 2026-11-22 21:33:05 +01:00
commit cc1fb178e2
7 files changed
+829 -192

No files matched your search

@@ -19,6 +19,8 @@ import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.bitchat.android.mesh.BluetoothMeshService
import com.bitchat.android.mesh.MeshService
import com.bitchat.android.geohash.LocationChannelManager
@@ -82,6 +84,13 @@ class MainActivity : OrientationAwareActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
if (pendingMeshForegroundServiceStart) {
startMeshForegroundServiceBestEffort()
}
}
})
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.setRecentsScreenshotEnabled(false)
}
@@ -603,8 +612,8 @@ class MainActivity : OrientationAwareActivity() {
}
try {
com.bitchat.android.service.MeshForegroundService.start(applicationContext)
pendingMeshForegroundServiceStart = false
pendingMeshForegroundServiceStart =
!com.bitchat.android.service.MeshForegroundService.start(applicationContext)
} catch (e: Exception) {
pendingMeshForegroundServiceStart = true
Log.w("MainActivity", "Unable to start foreground mesh service; will retry when activity is started", e)
@@ -737,13 +746,6 @@ class MainActivity : OrientationAwareActivity() {
}
}
override fun onStart() {
super.onStart()
if (pendingMeshForegroundServiceStart) {
startMeshForegroundServiceBestEffort()
}
}
override fun onResume() {
super.onResume()
// Revoke stale live-location work before any resumed UI can use cached channels.
@@ -36,26 +36,42 @@ class MeshForegroundService : Service() {
const val ACTION_QUIT = "com.bitchat.android.service.QUIT"
const val ACTION_UPDATE_NOTIFICATION = "com.bitchat.android.service.UPDATE_NOTIFICATION"
fun start(context: Context) {
/** Returns true when the service start request was accepted. */
fun start(context: Context): Boolean {
val intent = Intent(context, MeshForegroundService::class.java).apply { action = ACTION_START }
// Only launch as an FGS when onStartCommand can promote immediately.
val shouldStartForeground = shouldStartAsForeground(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (shouldStartForeground) {
context.startForegroundService(intent)
try {
context.startForegroundService(intent)
true
} catch (_: IllegalStateException) {
// Boot/background starts can be denied even with permissions.
// A later user-visible start can retry; never fall back to an
// illegal background service or crash the receiver/activity.
Log.i("MeshForegroundService", "Foreground service start deferred by system")
false
} catch (_: SecurityException) {
Log.i("MeshForegroundService", "Foreground service permission no longer available")
false
}
} else {
android.util.Log.i(
"MeshForegroundService",
"Not starting service on API>=26 (shouldStartForeground=$shouldStartForeground)"
)
false
}
} else {
if (MeshServicePreferences.isBackgroundEnabled(true)) {
context.startService(intent)
true
} else {
android.util.Log.i("MeshForegroundService", "Background disabled; not starting service (pre-O)")
false
}
}
}
@@ -113,17 +129,6 @@ class MeshForegroundService : Service() {
)
createChannel()
// Ensure mesh service exists in holder (create if needed)
val existing = MeshServiceHolder.meshService
if (existing != null) {
Log.d("MeshForegroundService", "Using existing BluetoothMeshService from holder")
} else {
val created = MeshServiceHolder.getOrCreate(applicationContext)
Log.i("MeshForegroundService", "Created new BluetoothMeshService via holder")
MeshServiceHolder.attach(created)
}
MeshServiceHolder.getUnifiedOrCreate(applicationContext)
// Notification content is driven by peer-state changes, not a permanent timer.
updateJob = scope.launch {
com.bitchat.android.services.AppStateStore.peers
@@ -185,37 +190,44 @@ class MeshForegroundService : Service() {
return START_NOT_STICKY
}
ACTION_UPDATE_NOTIFICATION -> {
// If we became eligible and are not in foreground yet, promote once
if (MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions() && !isInForeground) {
val count = getUnifiedActivePeerCount()
val n = buildNotification(count)
startForegroundCompat(n)
isInForeground = true
lastNotifiedPeerCount = count
} else {
if (isInForeground) {
updateNotification(force = true)
}
}
else -> { /* ACTION_START or null */ }
}
// Ensure mesh is running (only after permissions are granted)
ensureMeshStarted()
// Promote exactly once when eligible, otherwise stay background (or stop).
// POST_NOTIFICATIONS is intentionally not an eligibility requirement: Android 13+
// still allows foreground services and exposes them in the system task manager.
if (MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions() && !isInForeground) {
// ACTION_START comes from startForegroundService() on supported Android versions.
// Android still expects promotion if the background preference changed during dispatch.
val foregroundLaunch = intent?.action == ACTION_START
// Promote before constructing transports, loading identity storage, or starting
// mesh work. Android's foreground deadline includes time spent in onCreate().
if (!isInForeground && (foregroundLaunch || canRunInBackground())) {
val count = getUnifiedActivePeerCount()
val notification = buildNotification(count)
startForegroundCompat(notification)
if (!startForegroundCompat(notification)) {
stopSelf(startId)
return START_NOT_STICKY
}
isInForeground = true
lastNotifiedPeerCount = count
}
if (!isInForeground || !canRunInBackground()) {
if (isInForeground) stopForeground(true)
isInForeground = false
clearMeshNotifications()
stopSelf(startId)
return START_NOT_STICKY
}
ensureMeshStarted()
return START_STICKY
}
private fun canRunInBackground(): Boolean =
MeshServicePreferences.isBackgroundEnabled(true) && hasAllRequiredPermissions()
private fun ensureMeshStarted() {
if (isShuttingDown) return
try {
@@ -343,7 +355,7 @@ class MeshForegroundService : Service() {
return fine || coarse
}
private fun startForegroundCompat(notification: Notification) {
private fun startForegroundCompat(notification: Notification): Boolean = try {
if (Build.VERSION.SDK_INT >= 34) {
val type = if (hasLocationPermission()) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE or ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
@@ -355,8 +367,8 @@ class MeshForegroundService : Service() {
} catch (e: SecurityException) {
// Fallback for cases where "While In Use" permission exists but background start is restricted
if (type and ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION != 0) {
android.util.Log.w("MeshForegroundService", "Failed to start with LOCATION type, falling back to CONNECTED_DEVICE: ${e.message}")
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
Log.i("MeshForegroundService", "Location foreground type unavailable; trying connected device")
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
} else {
throw e
}
@@ -364,6 +376,13 @@ class MeshForegroundService : Service() {
} else {
startForeground(NOTIFICATION_ID, notification)
}
true
} catch (_: SecurityException) {
Log.i("MeshForegroundService", "Foreground promotion permission no longer available")
false
} catch (_: IllegalStateException) {
Log.i("MeshForegroundService", "Foreground promotion deferred by system")
false
}
override fun onDestroy() {
@@ -12,6 +12,7 @@ import android.system.OsConstants
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat
import com.bitchat.android.crypto.EncryptionService
import com.bitchat.android.mesh.DirectLinkAnnouncementPolicy
import com.bitchat.android.mesh.FragmentingPacketSender
@@ -115,7 +116,9 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
@Volatile private var subscribeSession: SubscribeDiscoverySession? = null
private val listenerExec = Executors.newCachedThreadPool()
@Volatile private var isActive = false
private val recoveryLock = Any()
@Volatile private var recoveryInProgress = false
private var startRequestedDuringRecovery = false
private val sessionGeneration = AtomicInteger(0)
private val consecutiveAttachFailures = AtomicInteger(0)
@@ -335,6 +338,10 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
])
override fun startServices() {
if (isActive) return
if (!hasDiscoveryPermission()) {
Log.i(TAG, "Wi-Fi Aware discovery permission unavailable; not starting")
return
}
if (!com.bitchat.android.wifiaware.WifiAwareController.enabled.value) {
Log.i(TAG, "Wi-Fi Aware transport disabled by debug settings; not starting")
return
@@ -348,28 +355,27 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
Log.i(TAG, "Wi-Fi Aware unavailable right now; not starting (${supportStatus.reason})")
return
}
if (recoveryInProgress) {
Log.i(TAG, "Wi-Fi Aware recovery cleanup still in progress; deferring start")
return
}
val manager = awareManager
if (manager == null || !manager.isAvailable) {
Log.w(TAG, "Wi-Fi Aware manager unavailable; not starting")
return
}
isActive = true
val generation = synchronized(recoveryLock) {
if (isActive) return
if (recoveryInProgress) {
startRequestedDuringRecovery = true
Log.i(TAG, "Wi-Fi Aware recovery cleanup still in progress; deferring start")
return
}
isActive = true
sessionGeneration.incrementAndGet()
}
val startTime = System.currentTimeMillis()
lastDiscoveryActivityAt.set(startTime)
lastDiscoveryRefreshAt.set(startTime)
val generation = sessionGeneration.incrementAndGet()
Log.i(TAG, "Starting Wi-Fi Aware mesh with peer ID: $myPeerID")
manager.attach(object : AttachCallback() {
@SuppressLint("MissingPermission")
@RequiresPermission(allOf = [
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.NEARBY_WIFI_DEVICES
])
val callback = object : AttachCallback() {
override fun onAttached(session: WifiAwareSession) {
if (!isCurrentSession(generation)) {
session.close()
@@ -377,135 +383,24 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
}
wifiAwareSession = session
consecutiveAttachFailures.set(0)
if (!hasDiscoveryPermission()) {
handleDiscoveryPermissionLoss(generation)
return
}
Log.i(TAG, "Wi-Fi Aware attached; starting publish & subscribe")
// PUBLISH (server role)
session.publish(
PublishConfig.Builder()
.setServiceName(SERVICE_NAME)
.setServiceSpecificInfo(myPeerID.toByteArray())
.build(),
object : DiscoverySessionCallback() {
override fun onPublishStarted(pub: PublishDiscoverySession) {
if (!isCurrentSession(generation)) {
pub.close()
return
}
publishSession = pub
Log.d(TAG, "Wi-Fi Aware publish started")
try { com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().addDebugMessage(com.bitchat.android.ui.debug.DebugMessage.SystemMessage("Wi-Fi Aware Publish Started")) } catch (_: Exception) {}
}
override fun onServiceDiscovered(
peerHandle: PeerHandle,
serviceSpecificInfo: ByteArray,
matchFilter: List<ByteArray>
) {
if (!isCurrentSession(generation)) return
val peerId = try { String(serviceSpecificInfo) } catch (_: Exception) { "" }
handleToPeerId[peerHandle] = peerId
if (peerId.isNotBlank()) {
rememberDiscoveredPeer(peerId)
publishHandles[peerId] = peerHandle
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
offerServerPathIfAppropriate(peerId, peerHandle, "publish discovery")
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onMessageReceived(
peerHandle: PeerHandle,
message: ByteArray
) {
if (!isCurrentSession(generation)) return
if (message.isEmpty()) return
val subscriberId = try { String(message) } catch (_: Exception) { "" }
if (subscriberId.startsWith(ROLE_REVERSAL_PREFIX)) {
val requesterId = subscriberId.removePrefix(ROLE_REVERSAL_PREFIX)
handleRoleReversalRequest(peerHandle, requesterId)
return
}
if (subscriberId == myPeerID) return
handleToPeerId[peerHandle] = subscriberId
if (subscriberId.isNotBlank()) {
rememberDiscoveredPeer(subscriberId)
publishHandles[subscriberId] = peerHandle
}
handleSubscriberPing(publishSession!!, peerHandle)
}
override fun onSessionTerminated() {
if (!isCurrentSession(generation)) return
publishSession = null
val shouldRestart = isActive && com.bitchat.android.wifiaware.WifiAwareController.enabled.value
Log.w(TAG, "Wi-Fi Aware publish session terminated (restart=$shouldRestart)")
handleUnexpectedStop(generation)
if (shouldRestart) {
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(2000)
try {
startDiscovery(session, generation)
} catch (_: SecurityException) {
handleDiscoveryPermissionLoss(generation)
}
}
},
Handler(Looper.getMainLooper())
)
// SUBSCRIBE (client role)
session.subscribe(
SubscribeConfig.Builder()
.setServiceName(SERVICE_NAME)
.setServiceSpecificInfo(myPeerID.toByteArray(Charsets.UTF_8))
.build(),
object : DiscoverySessionCallback() {
override fun onSubscribeStarted(sub: SubscribeDiscoverySession) {
if (!isCurrentSession(generation)) {
sub.close()
return
}
subscribeSession = sub
Log.d(TAG, "Wi-Fi Aware subscribe started")
try { com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().addDebugMessage(com.bitchat.android.ui.debug.DebugMessage.SystemMessage("Wi-Fi Aware Subscribe Started")) } catch (_: Exception) {}
}
override fun onServiceDiscovered(
peerHandle: PeerHandle,
serviceSpecificInfo: ByteArray,
matchFilter: List<ByteArray>
) {
if (!isCurrentSession(generation)) return
val peerId = try { String(serviceSpecificInfo) } catch (_: Exception) { "" }
handleToPeerId[peerHandle] = peerId
// This handle came from the subscribe session, so it is valid for
// subscribeSession.sendMessage() (used by maintenance reconnection).
if (peerId.isNotBlank()) subscribeHandles[peerId] = peerHandle
sendSubscribePing(peerId, peerHandle, "discovery")
if (peerId.isNotBlank()) rememberDiscoveredPeer(peerId)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onMessageReceived(
peerHandle: PeerHandle,
message: ByteArray
) {
if (!isCurrentSession(generation)) return
if (message.isEmpty()) return
handleServerReady(peerHandle, message)
}
override fun onSessionTerminated() {
if (!isCurrentSession(generation)) return
subscribeSession = null
val shouldRestart = isActive && com.bitchat.android.wifiaware.WifiAwareController.enabled.value
Log.w(TAG, "Wi-Fi Aware subscribe session terminated (restart=$shouldRestart)")
handleUnexpectedStop(generation)
if (shouldRestart) {
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(2000)
}
}
},
Handler(Looper.getMainLooper())
)
}
override fun onAttachFailed() {
if (!isCurrentSession(generation)) return
if (!hasDiscoveryPermission()) {
handleDiscoveryPermissionLoss(generation)
return
}
Log.e(TAG, "Wi-Fi Aware attach failed")
val retryDelayMs = attachRetryDelayMs(consecutiveAttachFailures.incrementAndGet())
handleUnexpectedStop(generation, retryDelayMs)
@@ -524,7 +419,14 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(3000)
}
}
}, Handler(Looper.getMainLooper()))
}
try {
manager.attach(callback, Handler(Looper.getMainLooper()))
} catch (_: SecurityException) {
handleDiscoveryPermissionLoss(generation)
return
}
if (!isCurrentSession(generation)) return
// Register with cross-layer transport bridge
TransportBridgeService.register("WIFI", this)
@@ -535,13 +437,145 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
connectionTracker.start()
}
@SuppressLint("MissingPermission")
private fun startDiscovery(session: WifiAwareSession, generation: Int) {
// PUBLISH (server role)
session.publish(
PublishConfig.Builder()
.setServiceName(SERVICE_NAME)
.setServiceSpecificInfo(myPeerID.toByteArray())
.build(),
object : DiscoverySessionCallback() {
override fun onPublishStarted(pub: PublishDiscoverySession) {
if (!isCurrentSession(generation)) {
pub.close()
return
}
publishSession = pub
Log.d(TAG, "Wi-Fi Aware publish started")
try { com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().addDebugMessage(com.bitchat.android.ui.debug.DebugMessage.SystemMessage("Wi-Fi Aware Publish Started")) } catch (_: Exception) {}
}
override fun onServiceDiscovered(
peerHandle: PeerHandle,
serviceSpecificInfo: ByteArray,
matchFilter: List<ByteArray>
) {
if (!isCurrentSession(generation)) return
val peerId = try { String(serviceSpecificInfo) } catch (_: Exception) { "" }
handleToPeerId[peerHandle] = peerId
if (peerId.isNotBlank()) {
rememberDiscoveredPeer(peerId)
publishHandles[peerId] = peerHandle
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
offerServerPathIfAppropriate(peerId, peerHandle, "publish discovery")
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onMessageReceived(
peerHandle: PeerHandle,
message: ByteArray
) {
if (!isCurrentSession(generation)) return
if (message.isEmpty()) return
val subscriberId = try { String(message) } catch (_: Exception) { "" }
if (subscriberId.startsWith(ROLE_REVERSAL_PREFIX)) {
val requesterId = subscriberId.removePrefix(ROLE_REVERSAL_PREFIX)
handleRoleReversalRequest(peerHandle, requesterId)
return
}
if (subscriberId == myPeerID) return
handleToPeerId[peerHandle] = subscriberId
if (subscriberId.isNotBlank()) {
rememberDiscoveredPeer(subscriberId)
publishHandles[subscriberId] = peerHandle
}
handleSubscriberPing(publishSession!!, peerHandle)
}
override fun onSessionTerminated() {
if (!isCurrentSession(generation)) return
publishSession = null
val shouldRestart = isActive && com.bitchat.android.wifiaware.WifiAwareController.enabled.value
Log.w(TAG, "Wi-Fi Aware publish session terminated (restart=$shouldRestart)")
handleUnexpectedStop(generation)
if (shouldRestart) {
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(2000)
}
}
},
Handler(Looper.getMainLooper())
)
// SUBSCRIBE (client role)
session.subscribe(
SubscribeConfig.Builder()
.setServiceName(SERVICE_NAME)
.setServiceSpecificInfo(myPeerID.toByteArray(Charsets.UTF_8))
.build(),
object : DiscoverySessionCallback() {
override fun onSubscribeStarted(sub: SubscribeDiscoverySession) {
if (!isCurrentSession(generation)) {
sub.close()
return
}
subscribeSession = sub
Log.d(TAG, "Wi-Fi Aware subscribe started")
try { com.bitchat.android.ui.debug.DebugSettingsManager.getInstance().addDebugMessage(com.bitchat.android.ui.debug.DebugMessage.SystemMessage("Wi-Fi Aware Subscribe Started")) } catch (_: Exception) {}
}
override fun onServiceDiscovered(
peerHandle: PeerHandle,
serviceSpecificInfo: ByteArray,
matchFilter: List<ByteArray>
) {
if (!isCurrentSession(generation)) return
val peerId = try { String(serviceSpecificInfo) } catch (_: Exception) { "" }
handleToPeerId[peerHandle] = peerId
// This handle came from the subscribe session, so it is valid for
// subscribeSession.sendMessage() (used by maintenance reconnection).
if (peerId.isNotBlank()) subscribeHandles[peerId] = peerHandle
sendSubscribePing(peerId, peerHandle, "discovery")
if (peerId.isNotBlank()) rememberDiscoveredPeer(peerId)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onMessageReceived(
peerHandle: PeerHandle,
message: ByteArray
) {
if (!isCurrentSession(generation)) return
if (message.isEmpty()) return
handleServerReady(peerHandle, message)
}
override fun onSessionTerminated() {
if (!isCurrentSession(generation)) return
subscribeSession = null
val shouldRestart = isActive && com.bitchat.android.wifiaware.WifiAwareController.enabled.value
Log.w(TAG, "Wi-Fi Aware subscribe session terminated (restart=$shouldRestart)")
handleUnexpectedStop(generation)
if (shouldRestart) {
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(2000)
}
}
},
Handler(Looper.getMainLooper())
)
}
/**
* Stops the Wi-Fi Aware mesh services and cleans up sockets and sessions.
*/
override fun stopServices() {
val wasActive = isActive
isActive = false
sessionGeneration.incrementAndGet()
val wasActive = synchronized(recoveryLock) {
val active = isActive
isActive = false
sessionGeneration.incrementAndGet()
startRequestedDuringRecovery = false
active
}
Log.i(TAG, "Stopping Wi-Fi Aware mesh")
// Unregister from bridge
@@ -584,13 +618,26 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
return generation == sessionGeneration.get() && isActive
}
private fun handleUnexpectedStop(generation: Int, restartDelayMs: Long = RECOVERY_RESTART_DELAY_MS) {
if (generation != sessionGeneration.get()) return
if (!isActive) {
return
private fun hasDiscoveryPermission(): Boolean {
val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
Manifest.permission.NEARBY_WIFI_DEVICES
} else {
Manifest.permission.ACCESS_FINE_LOCATION
}
return ContextCompat.checkSelfPermission(context, permission) == android.content.pm.PackageManager.PERMISSION_GRANTED
}
private fun handleDiscoveryPermissionLoss(generation: Int) {
Log.i(TAG, "Wi-Fi Aware discovery permission no longer available")
handleUnexpectedStop(generation, restartDelayMs = null)
}
private fun handleUnexpectedStop(generation: Int, restartDelayMs: Long? = RECOVERY_RESTART_DELAY_MS) {
synchronized(recoveryLock) {
if (!isCurrentSession(generation)) return
recoveryInProgress = true
isActive = false
}
recoveryInProgress = true
isActive = false
// Must follow isActive = false so a concurrent publish in the controller is either
// refused or overwritten here. Must precede the restart requests made by callers.
com.bitchat.android.wifiaware.WifiAwareController.onServiceInterrupted(this)
@@ -620,11 +667,16 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor
ingressLinks.clear()
}
} finally {
recoveryInProgress = false
// Recovery cleanup is done; nudge a restart now that startServices() will no
// longer be deferred by recoveryInProgress. The controller coalesces requests.
if (com.bitchat.android.wifiaware.WifiAwareController.enabled.value) {
com.bitchat.android.wifiaware.WifiAwareController.restartIfStillEnabled(restartDelayMs)
val retryDelayMs = synchronized(recoveryLock) {
val delayMs = restartDelayMs ?: 0L.takeIf { startRequestedDuringRecovery }
startRequestedDuringRecovery = false
recoveryInProgress = false
delayMs.takeIf { generation == sessionGeneration.get() }
}
// Permission loss alone does not retry. An eligible start requested during
// cleanup still gets a turn through the controller after cleanup finishes.
if (retryDelayMs != null && WifiAwareController.enabled.value && hasDiscoveryPermission()) {
WifiAwareController.restartIfStillEnabled(retryDelayMs)
}
}
}
@@ -0,0 +1,88 @@
package com.bitchat.android
import android.Manifest
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Lifecycle
import com.bitchat.android.service.MeshForegroundService
import com.bitchat.android.service.MeshServicePreferences
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mockStatic
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], application = Application::class)
class MainActivityForegroundServiceLifecycleRobolectricTest {
@Test
fun `pending foreground request runs on initial start and subsequent restart`() {
val app = RuntimeEnvironment.getApplication()
MeshServicePreferences.init(app)
MeshServicePreferences.setBackgroundEnabled(true)
shadowOf(app).grantPermissions(
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN
)
mockStatic(AppCompatDelegate::class.java).use { delegates ->
// Keep real Activity/lifecycle callbacks, without inflating AppCompat resources.
val delegate = mock<AppCompatDelegate>()
whenever(delegate.attachBaseContext2(any())).thenAnswer { it.getArgument<Context>(0) }
delegates.`when`<AppCompatDelegate> {
AppCompatDelegate.create(any<Activity>(), any())
}.thenReturn(delegate)
// The quit path initializes superclasses and skips transports and onboarding.
val intent = Intent(app, MainActivity::class.java).putExtra("ACTION_QUIT_APP", true)
val controller = Robolectric.buildActivity(MainActivity::class.java, intent).create()
val activity = controller.get()
Activity::class.java.getDeclaredField("mFinished").apply {
isAccessible = true
setBoolean(activity, false)
}
val request = MainActivity::class.java.getDeclaredMethod("startMeshForegroundServiceBestEffort")
.apply { isAccessible = true }
val pending = MainActivity::class.java.getDeclaredField("pendingMeshForegroundServiceStart")
.apply { isAccessible = true }
try {
assertEquals(Lifecycle.State.CREATED, activity.lifecycle.currentState)
request.invoke(activity)
assertTrue(pending.getBoolean(activity))
controller.start()
assertEquals(Lifecycle.State.STARTED, activity.lifecycle.currentState)
assertFalse("A real lifecycle start must consume the pending retry", pending.getBoolean(activity))
assertEquals(MeshForegroundService.ACTION_START, shadowOf(app).nextStartedService?.action)
controller.stop()
assertEquals(Lifecycle.State.CREATED, activity.lifecycle.currentState)
request.invoke(activity)
assertTrue(pending.getBoolean(activity))
controller.restart().start()
assertEquals(Lifecycle.State.STARTED, activity.lifecycle.currentState)
assertFalse("A later lifecycle start must also retry", pending.getBoolean(activity))
assertEquals(MeshForegroundService.ACTION_START, shadowOf(app).nextStartedService?.action)
controller.stop()
} finally {
controller.destroy()
}
}
}
}
@@ -0,0 +1,67 @@
package com.bitchat.android
import android.app.Application
import android.app.ForegroundServiceStartNotAllowedException
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import androidx.lifecycle.Lifecycle
import com.bitchat.android.service.MeshServicePreferences
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.*
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], application = Application::class)
class MainActivityForegroundServiceRetryRobolectricTest {
@Before
fun setUp() {
MeshServicePreferences.init(RuntimeEnvironment.getApplication())
MeshServicePreferences.setBackgroundEnabled(true)
}
@Test
fun `denied foreground start stays pending until an accepted retry`() {
assertRetryAfterDenial(ForegroundServiceStartNotAllowedException("synthetic transient denial"))
}
@Test
fun `permission denial stays pending until an accepted retry`() {
assertRetryAfterDenial(SecurityException("synthetic permission revocation"))
}
private fun assertRetryAfterDenial(denial: RuntimeException) {
val caller = mock<Context>()
whenever(caller.checkPermission(any(), any(), any())).thenReturn(PackageManager.PERMISSION_GRANTED)
whenever(caller.startForegroundService(any()))
.thenThrow(denial)
.thenReturn(ComponentName("com.bitchat.droid", "com.bitchat.android.service.MeshForegroundService"))
val lifecycle = mock<Lifecycle> {
on { currentState } doReturn Lifecycle.State.STARTED
}
// Attach without onCreate: the retry contract needs no transports, UI, or user data.
val activity = spy(Robolectric.buildActivity(MainActivity::class.java).get())
doReturn(caller).whenever(activity).applicationContext
doReturn(lifecycle).whenever(activity).lifecycle
val start = MainActivity::class.java.getDeclaredMethod("startMeshForegroundServiceBestEffort")
.apply { isAccessible = true }
start.invoke(activity)
val pending = MainActivity::class.java.getDeclaredField("pendingMeshForegroundServiceStart")
.apply { isAccessible = true }
assertTrue("Denied start must retain the activity retry", pending.getBoolean(activity))
verify(caller).startForegroundService(any())
start.invoke(activity)
verify(caller, times(2)).startForegroundService(any())
verify(caller, never()).startService(any())
assertFalse("An accepted retry must clear the pending flag", pending.getBoolean(activity))
}
}
@@ -0,0 +1,182 @@
package com.bitchat.android.service
import android.Manifest
import android.app.Application
import android.app.ForegroundServiceStartNotAllowedException
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import com.bitchat.android.mesh.BluetoothMeshService
import com.bitchat.android.mesh.UnifiedMeshService
import com.bitchat.android.R
import androidx.core.app.NotificationManagerCompat
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.*
import org.mockito.Mockito.mockConstruction
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [31, 34], application = Application::class)
class MeshForegroundServiceStartupTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before
fun setUp() {
MeshServicePreferences.init(context)
MeshServicePreferences.setBackgroundEnabled(true)
MeshServiceHolder.clear()
}
@After
fun tearDown() {
MeshServiceHolder.clear()
}
@Test
fun `background start rejection is deferred instead of crashing caller`() {
val caller = mock<Context>()
whenever(caller.checkPermission(any(), any(), any())).thenReturn(PackageManager.PERMISSION_GRANTED)
whenever(caller.startForegroundService(any())).thenThrow(
ForegroundServiceStartNotAllowedException("synthetic background denial"))
assertFalse(MeshForegroundService.start(caller))
verify(caller).startForegroundService(any())
verify(caller, never()).startService(any())
}
@Test
fun `foreground promotion rejection is contained`() {
val service = attachedService()
denyPromotion(service, ForegroundServiceStartNotAllowedException("synthetic promotion denial"))
assertFalse(promote(service))
}
@Test
fun `permission revocation during promotion is contained`() {
val service = attachedService()
denyPromotion(service, SecurityException("synthetic permission revocation"))
assertFalse(promote(service))
}
@Test
fun `promotion happens before mesh startup`() {
val events = mutableListOf<String>()
val bluetooth = mock<BluetoothMeshService> { on { isReusable() } doReturn true }
val unified = mock<UnifiedMeshService>()
MeshServiceHolder.attach(bluetooth)
MeshServiceHolder::class.java.getDeclaredField("unifiedMeshService").apply {
isAccessible = true
set(null, unified)
}
doAnswer { events.add("mesh"); null }.whenever(unified).startServices()
val service = attachedService()
doAnswer { events.add("foreground"); null }.whenever(service).startForeground(any(), any(), any())
doAnswer { events.add("foreground"); null }.whenever(service).startForeground(any(), any())
service.onStartCommand(Intent(context, MeshForegroundService::class.java).apply {
action = MeshForegroundService.ACTION_START
}, 0, 1)
assertEquals(listOf("foreground", "mesh"), events)
}
@Test
fun `denied promotion stops without mesh startup or sticky retry`() {
val bluetooth = mock<BluetoothMeshService> { on { isReusable() } doReturn true }
MeshServiceHolder.attach(bluetooth)
val service = attachedService()
denyPromotion(service, ForegroundServiceStartNotAllowedException("synthetic promotion denial"))
assertEquals(Service.START_NOT_STICKY, service.onStartCommand(null, 0, 7))
verify(service).stopSelf(7)
verify(bluetooth, never()).startServices()
verify(bluetooth, never()).isReusable()
}
@Test
fun `accepted foreground launch promotes before stopping after background mesh is disabled`() {
val service = attachedService()
stubNotificationCleanup(service)
val events = mutableListOf<String>()
doAnswer { events.add("promote"); null }.whenever(service).startForeground(any(), any(), any())
doAnswer { events.add("promote"); null }.whenever(service).startForeground(any(), any())
doAnswer { events.add("stop"); null }.whenever(service).stopSelf(8)
assertEquals(true, MeshForegroundService.start(context))
val request = shadowOf(RuntimeEnvironment.getApplication()).nextStartedService
MeshServicePreferences.setBackgroundEnabled(false)
assertEquals(Service.START_NOT_STICKY, service.onStartCommand(request, 0, 8))
assertEquals(listOf("promote", "stop"), events)
assertEquals(null, MeshServiceHolder.meshService)
}
@Test
fun `revoked permissions before dispatch stop without starting transports`() {
val service = attachedService()
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.BLUETOOTH_CONNECT)
stubNotificationCleanup(service)
assertEquals(Service.START_NOT_STICKY, service.onStartCommand(null, 0, 9))
verify(service).stopSelf(9)
verify(service, never()).startForeground(any(), any(), any())
verify(service, never()).startForeground(any(), any())
assertEquals(null, MeshServiceHolder.meshService)
}
@Test
fun `onCreate does not initialize mesh before promotion`() {
val bluetooth = mock<BluetoothMeshService> { on { isReusable() } doReturn true }
MeshServiceHolder.attach(bluetooth)
val service = attachedService()
doReturn("Mesh").whenever(service).getString(R.string.mesh_service_channel_name)
doReturn("Mesh service").whenever(service).getString(R.string.mesh_service_channel_desc)
mockConstruction(PeerAvailabilityNotifier::class.java).use {
try {
service.onCreate()
verifyNoInteractions(bluetooth)
} finally {
service.onDestroy()
}
}
}
private fun attachedService(): MeshForegroundService {
shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN)
return spy(Robolectric.buildService(MeshForegroundService::class.java).get()).apply {
doReturn("Bitchat").whenever(this).getString(R.string.app_name)
doReturn("Mesh running").whenever(this).getString(R.string.mesh_service_notification_content, 0)
doReturn("Quit").whenever(this).getString(R.string.notification_action_quit_bitchat)
}
}
private fun stubNotificationCleanup(service: MeshForegroundService) {
MeshForegroundService::class.java.getDeclaredField("notificationManager").apply {
isAccessible = true
set(service, NotificationManagerCompat.from(context))
}
MeshForegroundService::class.java.getDeclaredField("peerAvailabilityNotifier").apply {
isAccessible = true
set(service, mock<PeerAvailabilityNotifier>())
}
}
private fun promote(service: MeshForegroundService): Boolean =
MeshForegroundService::class.java.getDeclaredMethod("startForegroundCompat", Notification::class.java)
.apply { isAccessible = true }
.invoke(service, Notification.Builder(context, "synthetic").build()) as Boolean
private fun denyPromotion(service: MeshForegroundService, error: RuntimeException) {
doThrow(error).whenever(service).startForeground(any(), any(), any())
doThrow(error).whenever(service).startForeground(any(), any())
}
}
@@ -0,0 +1,227 @@
package com.bitchat.android.wifiaware
import android.Manifest
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.net.wifi.aware.AttachCallback
import android.net.wifi.aware.DiscoverySessionCallback
import android.net.wifi.aware.PublishDiscoverySession
import android.net.wifi.aware.WifiAwareManager
import android.net.wifi.aware.WifiAwareSession
import com.bitchat.android.crypto.EncryptionService
import com.bitchat.android.mesh.BluetoothMeshService
import com.bitchat.android.mesh.FragmentManager
import com.bitchat.android.mesh.MeshCore
import com.bitchat.android.service.MeshServiceHolder
import com.bitchat.android.service.TransportBridgeService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mockConstruction
import org.mockito.kotlin.*
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [32, 34], application = Application::class)
class WifiAwarePermissionRaceTest {
@Test
fun `permission revoked after attach is checked before discovery`() = withService { service, callback, session, scheduler ->
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
callback.onAttached(session)
scheduler.runCurrent()
assertFalse(service.isRunning())
assertFalse(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
verify(session, never()).publish(any(), any(), any())
verify(session).close()
}
@Test
fun `permission revoked inside publish is contained and session released`() = withService { service, callback, session, scheduler ->
doThrow(SecurityException("synthetic publish revocation")).whenever(session).publish(any(), any(), any())
callback.onAttached(session)
scheduler.runCurrent()
assertFalse(service.isRunning())
assertFalse(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
verify(session).close()
verify(session, never()).subscribe(any(), any(), any())
}
@Test
fun `permission revoked inside subscribe is contained and session released`() = withService { service, callback, session, scheduler ->
val publisher = mock<PublishDiscoverySession>()
doAnswer {
it.getArgument<DiscoverySessionCallback>(1).onPublishStarted(publisher)
null
}.whenever(session).publish(any(), any(), any())
doThrow(SecurityException("synthetic subscribe revocation")).whenever(session).subscribe(any(), any(), any())
callback.onAttached(session)
scheduler.runCurrent()
assertFalse(service.isRunning())
assertFalse(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
verify(session).close()
verify(publisher).close()
}
@Test
fun `attach permission denial does not start mesh work`() = withService(denyAttach = true) { service, _, _, scheduler ->
scheduler.runCurrent()
assertFalse(service.isRunning())
assertFalse(WifiAwareController.running.value)
}
@Test
fun `permission grant permits a later restart without discarding the service`() = withService { service, callback, session, scheduler ->
val app = RuntimeEnvironment.getApplication()
shadowOf(app).denyPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
callback.onAttached(session)
scheduler.runCurrent()
assertFalse(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
scheduler.advanceTimeBy(30_000)
scheduler.runCurrent()
assertFalse("Permission denial must not schedule an immediate restart", service.isRunning())
shadowOf(app).grantPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
WifiAwareController.startIfPossible()
assertTrue(service.isRunning())
assertTrue(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
}
@Test
fun `a start after permission regrant survives pending cleanup`() = withService { service, callback, session, scheduler ->
val app = RuntimeEnvironment.getApplication()
shadowOf(app).denyPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
callback.onAttached(session)
assertFalse(service.isRunning())
// Deliver the sole start request before the test dispatcher can finish cleanup.
shadowOf(app).grantPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
WifiAwareController.startIfPossible()
assertFalse(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
scheduler.runCurrent()
runBlocking {
withTimeout(10_000L) { WifiAwareController.running.first { it } }
}
assertTrue(service.isRunning())
assertTrue(WifiAwareController.running.value)
assertSame(service, WifiAwareController.getService())
}
@Test
fun `old cleanup cannot mark a replacement service inactive`() = withService { _, callback, session, scheduler ->
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
callback.onAttached(session)
val replacement = mock<WifiAwareMeshService> { on { isRunning() } doReturn true }
publishService(replacement)
scheduler.runCurrent()
assertTrue(WifiAwareController.running.value)
assertSame(replacement, WifiAwareController.getService())
}
private fun withService(denyAttach: Boolean = false,
test: (WifiAwareMeshService, AttachCallback, WifiAwareSession, TestCoroutineScheduler) -> Unit) {
val app = RuntimeEnvironment.getApplication()
val context = spy(app)
doReturn(context).whenever(context).applicationContext
shadowOf(app.packageManager).setSystemFeature(PackageManager.FEATURE_WIFI_AWARE, true)
shadowOf(app).grantPermissions(
Manifest.permission.NEARBY_WIFI_DEVICES, Manifest.permission.ACCESS_FINE_LOCATION)
val manager = mock<WifiAwareManager> { on { isAvailable } doReturn true }
doReturn(manager).whenever(context).getSystemService(WifiAwareManager::class.java)
val locationManager = mock<LocationManager> { on { isLocationEnabled } doReturn true }
doReturn(locationManager).whenever(context).getSystemService(Context.LOCATION_SERVICE)
val contextField = WifiAwareController::class.java.getDeclaredField("appContext").apply { isAccessible = true }
val previousContext = contextField.get(null)
contextField.set(null, context)
val enabledField = WifiAwareController::class.java.getDeclaredField("_enabled").apply { isAccessible = true }
@Suppress("UNCHECKED_CAST")
val enabled = enabledField.get(null) as MutableStateFlow<Boolean>
enabled.value = true
MeshServiceHolder.attach(mock<BluetoothMeshService> { on { isReusable() } doReturn true })
val scheduler = TestCoroutineScheduler()
val scope = CoroutineScope(StandardTestDispatcher(scheduler) + SupervisorJob())
var callback: AttachCallback? = null
doAnswer {
callback = it.getArgument(0)
if (denyAttach) throw SecurityException("synthetic attach revocation")
null
}.whenever(manager).attach(any(), any())
try {
mockConstruction(EncryptionService::class.java) { crypto, _ ->
whenever(crypto.getIdentityFingerprint()).thenReturn("1111222233334444")
}.use {
mockConstruction(com.bitchat.android.ui.NotificationManager::class.java).use {
mockConstruction(MeshCore::class.java) { core, _ ->
whenever(core.fragmentManager).thenReturn(FragmentManager())
}.use { cores ->
val service = WifiAwareMeshService(context)
WifiAwareMeshService::class.java.getDeclaredField("serviceScope").apply {
isAccessible = true
(get(service) as CoroutineScope).cancel()
set(service, scope)
}
service.startServices()
checkNotNull(callback) { "Expected a real attach request" }
if (!denyAttach) {
// Production publishes the service before asynchronous attachment completes.
publishService(service)
}
test(service, callback!!, mock(), scheduler)
if (denyAttach) verify(cores.constructed().single(), never()).startCore()
}
}
}
} finally {
enabled.value = false
publishService(null)
contextField.set(null, previousContext)
scope.cancel()
TransportBridgeService.unregister("WIFI")
MeshServiceHolder.clear()
}
}
private fun publishService(service: WifiAwareMeshService?) {
WifiAwareController::class.java.getDeclaredField("service").apply {
isAccessible = true
set(null, service)
}
@Suppress("UNCHECKED_CAST")
val running = WifiAwareController::class.java.getDeclaredField("_running").apply {
isAccessible = true
}.get(null) as MutableStateFlow<Boolean>
running.value = service?.isRunning() == true
}
}