diff --git a/app/src/main/kotlin/com/tutpro/baresip/BaresipService.kt b/app/src/main/kotlin/com/tutpro/baresip/BaresipService.kt index 6ef7f58b..a3972aff 100644 --- a/app/src/main/kotlin/com/tutpro/baresip/BaresipService.kt +++ b/app/src/main/kotlin/com/tutpro/baresip/BaresipService.kt @@ -95,6 +95,7 @@ class BaresipService: Service() { private lateinit var wm: WifiManager private lateinit var tm: TelecomManager private lateinit var vibrator: Vibrator + private lateinit var partialWakeLock: PowerManager.WakeLock private lateinit var proximityWakeLock: PowerManager.WakeLock private lateinit var wifiLock: WifiManager.WifiLock private lateinit var hotSpotReceiver: BroadcastReceiver @@ -155,6 +156,12 @@ class BaresipService: Service() { applicationContext.getSystemService(VIBRATOR_SERVICE) as Vibrator } + // This is needed to keep service running also in Doze Mode + partialWakeLock = pm.newWakeLock( + PowerManager.PARTIAL_WAKE_LOCK, + "com.tutpro.baresip:wakelock" + ).apply { setReferenceCounted(false) } + networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { @@ -1333,7 +1340,8 @@ class BaresipService: Service() { callActionUri = "" Log.d(TAG, "Battery optimizations are ignored: " + "${pm.isIgnoringBatteryOptimizations(packageName)}") - Log.d(TAG, "WiFi lock is held: ${wifiLock.isHeld}") + Log.d(TAG, "Partial wake lock/wifi lock is held: " + + "${partialWakeLock.isHeld}/${wifiLock.isHeld}") updateStatusNotification() } @@ -1534,8 +1542,32 @@ class BaresipService: Service() { Log.e(TAG, "Failed to update foreground notification: ${e.message}") nm.notify(STATUS_NOTIFICATION_ID, notification) } + + updatePartialWakeLock() } - + + @SuppressLint("WakelockTimeout") + private fun updatePartialWakeLock() { + val isAnyUaActive = uasStatus.value.values.any { it != R.drawable.circle_white } + val isAnyCallActive = calls.isNotEmpty() + val needsToStayAwake = isAnyUaActive || isAnyCallActive + try { + if (needsToStayAwake) { + if (!partialWakeLock.isHeld) { + Log.d(TAG, "Acquiring Partial Wake Lock (UA Active or Call in progress)") + partialWakeLock.acquire() + } + } else { + if (partialWakeLock.isHeld) { + Log.d(TAG, "Releasing Partial Wake Lock (All UAs idle and no calls)") + partialWakeLock.release() + } + } + } catch (e: Exception) { + Log.e(TAG, "Error managing partialWakeLock: ${e.message}") + } + } + private fun toast(message: String, length: Int = Toast.LENGTH_SHORT) { Handler(Looper.getMainLooper()).post { Toast.makeText(this@BaresipService.applicationContext, message, length).show() @@ -1976,6 +2008,8 @@ class BaresipService: Service() { messages = emptyList() if (this::nm.isInitialized) nm.cancelAll() + if (this::partialWakeLock.isInitialized && partialWakeLock.isHeld) + partialWakeLock.release() if (this::proximityWakeLock.isInitialized && proximityWakeLock.isHeld) proximityWakeLock.release() if (this::wifiLock.isInitialized)