communicate: ring for incoming SIM calls (#856)
- Commit
09e28dadc50bc327ba42d44c1ee2cd99cc55306b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 17:37 UTC (23 days ago)
- Parents
d65f1b2
Symptom: with Communicate as the default phone app, an incoming
carrier (SIM) call showed only a silent heads-up notification and the
call screen. Nothing rang and nothing vibrated.
Root cause: three choices that were each fine alone left nobody
playing the ringtone.
- The manifest declares android.telecom.IN_CALL_SERVICE_RINGING=true
on CommunicateInCallService, which tells Telecom's own Ringer to
skip the ringtone, the vibration and the call-waiting tone because
the dialer plays them.
- The SIM incoming-call notification channel is deliberately muted so
it would not ding over the "system" ringtone.
- CallRinger, which rings WhatsApp/Signal/Google Voice calls since
bcfbcfc1c, excluded SIM calls on the assumption that the platform
rings them.
Changes:
- SimRingController (new, telephony/) derives ringing from every SIM
leg Telecom holds and drives CallRinger: start when a leg enters
STATE_RINGING (or STATE_SIMULATED_RINGING after call-screening audio
processing), stop on answer, reject, local or remote disconnect, or
when another call is answered. CommunicateInCallService now
registers its Call.Callback on every leg rather than only the most
recent one, so the ringer sees a call-waiting leg arrive and the
call it waits behind end. onSilenceRinger (volume/power key) mutes
the ring for that call, and a call-screening service's
EXTRA_SILENT_RINGING_REQUESTED is honoured.
- Call waiting follows AOSP Telecom: a ringing leg while another call
is up (another SIM leg, or a WhatsApp/Signal/Google Voice call via
the new LiveCalls probe) plays only the call-waiting tone,
ToneGenerator.TONE_SUP_CALL_WAITING on STREAM_VOICE_CALL at relative
volume 80 (a short beep in the earpiece roughly every 10 s), with no
ringtone and no vibration. If the active call ends while the waiting
call still rings, it switches to the full ring. The same rule
applies to VoIP calls arriving during a carrier call.
- CallRinger now takes a RingRequest (line, call key, caller number,
call-waiting flag). Starts are idempotent per call; a line can only
stop or silence its own ring, so a VoIP service's state updates can
no longer cut off a ringing SIM call. Connection.onSilence on the
WhatsApp/Signal and Google Voice connections mutes their ring too.
- How it alerts is a pure function, domain/RingPolicy.kt ringPlan(),
fed by RingEnvironmentReader:
- Ringer mode: silent plays nothing and does not vibrate (the old
ringer vibrated even in silent mode); vibrate only vibrates;
normal plays the ringtone when the ring volume is above zero and
vibrates per "vibrate for calls" (ring_vibration_intensity on
Android 13+, VIBRATE_WHEN_RINGING before). Vibration uses
VibrationAttributes.USAGE_RINGTONE on 13+, so the system's own
ring-intensity and silent-mode gating also applies.
- Do Not Disturb: NotificationManager.matchesCallFilter(tel:<number>)
on Android 13+, which lets starred contacts and repeat callers
through exactly as the policy says. When there is no dialable
number (private caller, Signal ACI, WhatsApp @lid) or the check is
unavailable, the active DND policy is applied to the contact
lookup (calls category, anyone/contacts/starred). A filtered call
gets no sound, vibration or call-waiting tone; its notification
still shows.
- Custom ringtones: the caller's ContactsContract CUSTOM_RINGTONE
via PhoneLookup, falling back to the default ringtone when unset,
blank, or unplayable (deleted file). Audio stays
USAGE_NOTIFICATION_RINGTONE.
- VoIP peers get a dialable number from their id (WhatsApp JID user
part, Signal E.164, Google Voice number) so the same DND and
custom-ringtone rules apply to them.
- Full-screen intent kept on all three incoming-call notifications,
now attached through setCallFullScreenIntent(): on Android 14+ when
canUseFullScreenIntent() is false it is left off (logged once) and
the call posts as the CallStyle heads-up with answer/decline, still
ringing, instead of relying on an intent the system would drop.
- Notification channels stay silent: CallRinger owns all call audio.
Alternatives rejected: dropping IN_CALL_SERVICE_RINGING to let
Telecom ring would fix SIM calls but leave the VoIP lines on a
separate ringer with different rules, and the in-app call screen
already owns the ringing UI.
User-visible effect: SIM calls ring (and vibrate per settings) when
Communicate is the default phone app; every line now respects silent
and vibrate modes, Do Not Disturb and per-contact ringtones; a second
call during a call beeps instead of ringing over it.
Verification: new unit tests RingPolicyTest (ringer mode x vibrate
setting x DND x call waiting, DND policy fallback, number extraction)
and SimRingControllerTest (start/stop over call-state transitions,
call waiting, silence, call screening, with a fake ringer);
CallRingerSlice4Test moved to the new API and now also covers silent,
vibrate and call-waiting modes, per-line stop and silence.
:communicate:compileDevKotlin, testDevUnitTest, lint and detekt in the
toolchain container.
On-device check (Communicate as default phone app): call the SIM from
another phone in normal, vibrate and silent mode; with DND on, from a
non-starred and a starred contact and twice within 15 minutes; from a
contact with a custom ringtone; a second call during an active call
(call-waiting beep, full ring after hanging up the first); volume key
while ringing; and a WhatsApp/Google Voice call in normal and silent
mode.Diff
communicate/src/main/java/com/vayunmathur/communicate/domain/RingPolicy.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/domain/RingPolicy.kt b/communicate/src/main/java/com/vayunmathur/communicate/domain/RingPolicy.ktnew file mode 100644index 0000000000..f7fa090b34--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/domain/RingPolicy.kt@@ -0,0 +1,115 @@+package com.vayunmathur.communicate.domain++/** The device ringer switch, as `AudioManager.getRingerMode()` reports it. */+enum class RingerMode { Silent, Vibrate, Normal }++/**+ * Everything that decides how one incoming call alerts, already read from the system.+ *+ * @property ringVolumeAudible whether the ring stream volume is above zero.+ * @property vibrateWhenRinging the "vibrate for calls" system setting; only consulted in [RingerMode.Normal],+ * since [RingerMode.Vibrate] always vibrates and [RingerMode.Silent] never does.+ * @property callerAllowedByDnd whether Do Not Disturb lets this caller through (true when DND is off).+ * @property otherCallLive whether another call is already up, which makes this one a call-waiting call.+ */+data class RingConditions(+ val ringerMode: RingerMode,+ val ringVolumeAudible: Boolean,+ val vibrateWhenRinging: Boolean,+ val callerAllowedByDnd: Boolean,+ val otherCallLive: Boolean,+)++/** What the ringer should do for one incoming call. All false means the call alerts visually only. */+data class RingPlan(+ val ringtone: Boolean,+ val vibrate: Boolean,+ val callWaitingTone: Boolean,+) {+ /** Whether nothing audible or haptic plays. */+ val isSilent: Boolean get() = !ringtone && !vibrate && !callWaitingTone++ /** Named plans, so call sites and tests read as the behaviour rather than three booleans. */+ companion object {+ val Silent = RingPlan(ringtone = false, vibrate = false, callWaitingTone = false)+ val VibrateOnly = RingPlan(ringtone = false, vibrate = true, callWaitingTone = false)+ val CallWaiting = RingPlan(ringtone = false, vibrate = false, callWaitingTone = true)+ }+}++/**+ * Decide how an incoming call alerts, following AOSP Telecom's `Ringer`:+ *+ * - A caller Do Not Disturb filters out gets nothing at all (the notification still shows).+ * - A second call while another is live gets only the call-waiting tone, which plays in the earpiece+ * of the call already up — never the full ringtone, and no vibration. The ringer switch does not+ * silence it, because it is in-call audio rather than a ring.+ * - Otherwise the ringer switch rules: silent plays nothing, vibrate only vibrates, and normal plays+ * the ringtone (when the ring volume is above zero) and vibrates when "vibrate for calls" is on.+ */+fun ringPlan(conditions: RingConditions): RingPlan = when {+ !conditions.callerAllowedByDnd -> RingPlan.Silent+ conditions.otherCallLive -> RingPlan.CallWaiting+ conditions.ringerMode == RingerMode.Silent -> RingPlan.Silent+ conditions.ringerMode == RingerMode.Vibrate -> RingPlan.VibrateOnly+ else -> RingPlan(+ ringtone = conditions.ringVolumeAudible,+ vibrate = conditions.vibrateWhenRinging,+ callWaitingTone = false,+ )+}++/** The Do Not Disturb interruption filter, as `NotificationManager.getCurrentInterruptionFilter()` reports it. */+enum class DndMode { Off, PriorityOnly, AlarmsOnly, TotalSilence }++/** Which callers a priority-only Do Not Disturb policy lets through. */+enum class DndCallers { None, Anyone, Contacts, Starred }++/**+ * A Do Not Disturb policy, reduced to what matters for calls.+ *+ * @property callsAllowed whether the policy's priority categories include calls at all.+ */+data class DndPolicy(+ val mode: DndMode,+ val callsAllowed: Boolean,+ val callers: DndCallers,+)++/**+ * Whether [policy] lets a call through, for when the platform's own caller check+ * (`NotificationManager.matchesCallFilter`) cannot answer — no dialable number, or the check is+ * unavailable. Repeat callers cannot be judged from here, so they only break through via that check.+ */+fun dndAllowsCall(policy: DndPolicy, isContact: Boolean, isStarred: Boolean): Boolean = when (policy.mode) {+ DndMode.Off -> true+ DndMode.AlarmsOnly, DndMode.TotalSilence -> false+ DndMode.PriorityOnly -> policy.callsAllowed && when (policy.callers) {+ DndCallers.Anyone -> true+ DndCallers.Contacts -> isContact || isStarred+ DndCallers.Starred -> isStarred+ DndCallers.None -> false+ }+}++private val DIALABLE_NUMBER = Regex("""\+?\d{3,15}""")++/** Formatting a stored or typed number may carry; stripped before the digits are checked. */+private const val NUMBER_PUNCTUATION = " -()."++/**+ * The phone number inside a line-specific peer id, or null when the peer has none.+ *+ * Google Voice and SIM peers are plain numbers; WhatsApp peers are JIDs (`[email protected]`,+ * with an optional `:device` suffix); Signal peers are an ACI (a UUID) or an E.164 number. WhatsApp+ * `@lid` ids are opaque digits, not numbers, so they are rejected. The number feeds the contact lookup+ * (custom ringtone, starred) and the Do Not Disturb caller check.+ */+fun dialableNumberOrNull(peerId: String): String? {+ val trimmed = peerId.trim()+ val domain = trimmed.substringAfter('@', missingDelimiterValue = "")+ if (domain == "lid") return null+ val user = trimmed.substringBefore('@').substringBefore(':')+ val compact = user.filterNot { it in NUMBER_PUNCTUATION }+ return compact.takeIf { DIALABLE_NUMBER.matches(it) }+}
communicate/src/main/java/com/vayunmathur/communicate/notifications/CallFullScreenIntent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/notifications/CallFullScreenIntent.kt b/communicate/src/main/java/com/vayunmathur/communicate/notifications/CallFullScreenIntent.ktnew file mode 100644index 0000000000..e1f9df83a9--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/notifications/CallFullScreenIntent.kt@@ -0,0 +1,36 @@+package com.vayunmathur.communicate.notifications++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.os.Build+import com.vayunmathur.library.log.Log++private const val TAG = "CallFullScreenIntent"++@Volatile+private var reportedFullScreenDenied = false++/**+ * Attach the incoming-call full-screen intent when the app may use it.+ *+ * Android 14 made `USE_FULL_SCREEN_INTENT` a special app access the user (or the store) can revoke, and+ * a revoked app's full-screen intent is silently dropped. When+ * [NotificationManager.canUseFullScreenIntent] says no, this leaves the intent off and the call shows as+ * the `CallStyle` heads-up notification instead — still with answer / decline, still ringing via+ * `CallRinger` — rather than a notification that claims a full-screen treatment it will not get.+ */+fun Notification.Builder.setCallFullScreenIntent(context: Context, intent: PendingIntent): Notification.Builder {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ val nm = context.getSystemService(NotificationManager::class.java)+ if (nm != null && !nm.canUseFullScreenIntent()) {+ if (!reportedFullScreenDenied) {+ reportedFullScreenDenied = true+ Log.status(TAG, "full-screen intent access revoked; incoming calls post as heads-up only")+ }+ return this+ }+ }+ return setFullScreenIntent(intent, true)+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/CallRinger.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/CallRinger.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/CallRinger.ktindex ed4cd91582..c59cce1518 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/CallRinger.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/CallRinger.kt@@ -2,103 +2,234 @@ package com.vayunmathur.communicate.telephony import android.content.Context import android.media.AudioAttributes+import android.media.AudioManager import android.media.MediaPlayer import android.media.RingtoneManager+import android.media.ToneGenerator+import android.net.Uri+import android.os.Build+import android.os.VibrationAttributes import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager+import com.vayunmathur.communicate.domain.ringPlan import com.vayunmathur.library.log.Log +/** Which call stack a ring belongs to. A line can only stop or silence its own ring. */+enum class RingLine { Sim, InApp, GoogleVoice }++/**+ * One incoming call asking to ring.+ *+ * @property callKey identifies the call, so repeating the same request (every state or details change+ * re-sends it) is a no-op instead of restarting the ringtone.+ * @property number the caller's dialable number, or null for private callers and peers without one (a+ * Signal ACI). Drives the Do Not Disturb caller check and the contact's custom ringtone.+ * @property callWaiting whether another call is already live, which turns the ring into the+ * call-waiting tone.+ */+data class RingRequest(+ val line: RingLine,+ val callKey: Any,+ val number: String?,+ val callWaiting: Boolean,+)++/** The ringer as call-state code sees it; [CallRinger] in production, a recording fake in tests. */+interface IncomingRinger {+ fun ring(request: RingRequest)++ fun stop(line: RingLine)+}+ /** * Audible + haptic ringing for incoming calls, shared by every line. *- * Self-managed Telecom connections ([InAppCallConnectionService],- * [GoogleVoiceConnectionService]) post an incoming-call notification — but no notification (even a- * `CallStyle` one) loops the ringtone by itself, and none of the call paths- * played anything. The result was exactly the reported bug: a silent heads-up- * notification instead of a ringing call. Carrier/SIM calls are excluded: the- * platform already plays the ringtone for dialer-role calls, and a second- * loop would double it.+ * Nothing else rings for Communicate's calls:+ * - Self-managed Telecom connections ([InAppCallConnectionService], [GoogleVoiceConnectionService])+ * never get a ringtone from the platform, and no notification (even a `CallStyle` one) loops one.+ * - Carrier/SIM calls do not either: [CommunicateInCallService] declares `IN_CALL_SERVICE_RINGING`,+ * which tells Telecom's own `Ringer` to skip the ringtone, the vibration and the call-waiting tone+ * because the dialer plays them. Before #856 nobody did, so SIM calls arrived as a silent heads-up. *- * One singleton rather than one per service because only one call can ring at- * a time, and because answer/decline can arrive from the system surface, the- * notification action, or the in-app screen — whichever path leaves- * `Incoming` first stops the same ringer. Start is idempotent; stop always- * releases.+ * Every incoming-call notification channel stays silent: the ringer owns audio, otherwise a channel+ * ding would double up with the loop. *- * Sound is the user's default ringtone looped through- * `USAGE_NOTIFICATION_RINGTONE` (so silent/DND modes are honoured by the platform), plus the- * standard ring-vibrate waveform. The incoming-call notifications themselves stay- * silent — the ringer owns audio, otherwise the channel's ding would double- * up with the loop.+ * What plays is decided by [ringPlan] from [RingEnvironmentReader]: the ringer switch (silent, vibrate,+ * normal), the "vibrate for calls" setting, Do Not Disturb (with the platform's starred-contact and+ * repeat-caller exceptions), and whether another call is up (call-waiting tone only). The ringtone is+ * the caller's contact ringtone when set, else the default, played through `USAGE_NOTIFICATION_RINGTONE`.+ *+ * One singleton rather than one per service because only one call rings at a time, and because+ * answer/decline can arrive from the system surface, the notification action, or the in-app screen —+ * whichever path leaves ringing first stops the same ringer. */ object CallRinger { private const val TAG = "CallRinger" + /** Relative volume of AOSP Telecom's call-waiting tone (`InCallTonePlayer.RELATIVE_VOLUME_HIPRI`). */+ private const val CALL_WAITING_TONE_VOLUME = 80++ /** The standard ring-vibrate waveform: 1 s on, 1 s off, repeating from index 0. */+ private val RING_VIBRATION_PATTERN = longArrayOf(0, 1000, 1000)++ private val ringtoneAudioAttributes: AudioAttributes = AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .build()++ /** The call currently ringing (or silenced while still ringing); null when idle. */+ @Volatile+ private var current: RingRequest? = null+ @Volatile private var player: MediaPlayer? = null @Volatile private var vibrator: Vibrator? = null - /** Idempotent: a second incoming call while ringing keeps the same loop. */+ @Volatile+ private var toneGenerator: ToneGenerator? = null++ /**+ * Start alerting for [request]. Idempotent per call: the same line, call and call-waiting status is a+ * no-op, so a silenced call stays silent. A different call, or the same call switching between+ * call-waiting and a full ring (the other call hung up), replaces what is playing.+ */ @Synchronized- fun start(context: Context) {- if (player != null) return+ fun start(context: Context, request: RingRequest) {+ if (current?.sameRing(request) == true) return+ releasePlayback()+ current = request val app = context.applicationContext- startVibration(app)- startSound(app)+ val environment = RingEnvironmentReader.read(app, request)+ val plan = ringPlan(environment.conditions)+ Log.status(TAG, "incoming ${request.line} call: $plan from ${environment.conditions}")+ if (plan.callWaitingTone) startCallWaitingTone()+ if (plan.vibrate) startVibration(app)+ if (plan.ringtone) startSound(app, environment.customRingtone) } + /** The call on [line] stopped ringing (answered, rejected, ended). Another line's ring is left alone. */ @Synchronized- fun stop() {+ fun stop(line: RingLine) {+ if (current?.line != line) return+ releasePlayback()+ current = null+ }++ /**+ * Mute the ring on [line] while the call keeps ringing — the volume or power key, delivered as+ * `InCallService.onSilenceRinger` / `Connection.onSilence`. The request is kept so the line's+ * next [start] for the same call stays a no-op.+ */+ @Synchronized+ fun silence(line: RingLine) {+ if (current?.line != line) return+ Log.status(TAG, "incoming $line call silenced")+ releasePlayback()+ }++ /** [IncomingRinger] view of this ringer for a call surface holding [context]. */+ fun asIncomingRinger(context: Context): IncomingRinger = object : IncomingRinger {+ override fun ring(request: RingRequest) = start(context, request)++ override fun stop(line: RingLine) = [email protected](line)+ }++ private fun RingRequest.sameRing(other: RingRequest): Boolean =+ line == other.line && callKey == other.callKey && callWaiting == other.callWaiting++ private fun releasePlayback() { runCatching { player?.stop() } runCatching { player?.release() } player = null runCatching { vibrator?.cancel() } vibrator = null+ runCatching { toneGenerator?.stopTone() }+ runCatching { toneGenerator?.release() }+ toneGenerator = null+ }++ /**+ * AOSP Telecom's call-waiting tone: `TONE_SUP_CALL_WAITING` on the voice-call stream, so it plays+ * in the earpiece of the call already up. The tone's own pattern repeats a short beep about every+ * ten seconds until [releasePlayback] stops it.+ */+ private fun startCallWaitingTone() {+ runCatching {+ ToneGenerator(AudioManager.STREAM_VOICE_CALL, CALL_WAITING_TONE_VOLUME).also {+ it.startTone(ToneGenerator.TONE_SUP_CALL_WAITING)+ }+ }.onSuccess {+ toneGenerator = it+ }.onFailure {+ Log.status(TAG, "could not start the call-waiting tone", it)+ } } + /**+ * Ringtone-usage vibration. On Android 13+ [VibrationAttributes.USAGE_RINGTONE] also lets the system+ * apply the user's ring vibration intensity and silent mode itself, on top of [ringPlan].+ */ private fun startVibration(app: Context) { runCatching { val vib = app.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return+ val effect = VibrationEffect.createWaveform(RING_VIBRATION_PATTERN, 0)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ vib.vibrate(effect, VibrationAttributes.createForUsage(VibrationAttributes.USAGE_RINGTONE))+ } else {+ @Suppress("DEPRECATION")+ vib.vibrate(effect, ringtoneAudioAttributes)+ } vibrator = vib- vib.vibrate(VibrationEffect.createWaveform(longArrayOf(0, 1000, 1000), 0)) }.onFailure { Log.status(TAG, "could not start call vibration", it) } } - private fun startSound(app: Context) {- val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)+ /** Plays [customRingtone] when the caller has one, falling back to the default ringtone if it fails. */+ private fun startSound(app: Context, customRingtone: Uri?) {+ val default = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)- ?: return+ val uri = customRingtone ?: default ?: return+ playLooping(app, uri, fallback = default?.takeIf { customRingtone != null && it != customRingtone })+ }++ private fun playLooping(app: Context, uri: Uri, fallback: Uri?) {+ val mp = MediaPlayer() runCatching {- MediaPlayer().apply {- setDataSource(app, uri)- setAudioAttributes(- AudioAttributes.Builder()- .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)- .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)- .build(),- )- isLooping = true- setOnPreparedListener { mp ->- // stop() may have run while prepare was in flight; only start the- // current generation, otherwise a stale callback re-rings after hangup.- if (mp === player) runCatching { mp.start() } else runCatching { mp.release() }+ mp.setDataSource(app, uri)+ mp.setAudioAttributes(ringtoneAudioAttributes)+ mp.isLooping = true+ mp.setOnPreparedListener { prepared ->+ // stop() may have run while prepare was in flight; only start the current+ // generation, otherwise a stale callback re-rings after hangup.+ synchronized(this) {+ if (prepared === player) runCatching { prepared.start() } else runCatching { prepared.release() } }- setOnErrorListener { _, _, _ ->- Log.status(TAG, "ringtone playback failed for $uri")- true+ }+ mp.setOnErrorListener { failed, what, extra ->+ Log.status(TAG, "ringtone playback failed what=$what extra=$extra")+ synchronized(this) {+ if (failed === player && fallback != null) {+ runCatching { failed.release() }+ player = null+ playLooping(app, fallback, fallback = null)+ } }- // Async: prepare() blocks (content-resolver IO) and this is- // called from the service's main-thread state collector.- prepareAsync()- }.also { player = it }+ true+ }+ // Async: prepare() blocks (content-resolver IO) and this is called from the+ // services' state callbacks.+ mp.prepareAsync()+ }.onSuccess {+ player = mp }.onFailure {- Log.status(TAG, "could not start ringtone for $uri", it)- player = null+ runCatching { mp.release() }+ Log.status(TAG, "could not start the ringtone (custom=${fallback != null})", it)+ // A deleted or unreadable contact ringtone still rings, with the default.+ if (fallback != null) playLooping(app, fallback, fallback = null) } } }
communicate/src/main/java/com/vayunmathur/communicate/telephony/CommunicateInCallService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/CommunicateInCallService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/CommunicateInCallService.ktindex 7f90304f00..96431fb04d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/CommunicateInCallService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/CommunicateInCallService.kt@@ -13,6 +13,7 @@ import com.vayunmathur.communicate.MainActivity import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.findContactName+import com.vayunmathur.communicate.notifications.setCallFullScreenIntent import com.vayunmathur.library.util.deleteNotificationChannel import com.vayunmathur.library.util.ensureNotificationChannel @@ -21,19 +22,28 @@ import com.vayunmathur.library.util.ensureNotificationChannel * * Owns the system call surface (notification controls) and mirrors the call into [SimCallBridge] so the * shared in-app call screen serves regular phone calls too — with the dial pad voicemail needs.+ *+ * Also rings: the manifest declares `IN_CALL_SERVICE_RINGING`, so Telecom plays neither the ringtone nor+ * the call-waiting tone for carrier calls and [SimRingController] drives [CallRinger] instead (#856).+ * Every leg gets the callback, not just [currentCall], so the ringer sees a call-waiting leg arrive and+ * the call it is waiting behind end. */ class CommunicateInCallService : InCallService() { + private val ringController by lazy {+ SimRingController(CallRinger.asIncomingRinger(this)) { LiveCalls.otherThan(RingLine.Sim) }+ }+ private val callback = object : Call.Callback() { override fun onStateChanged(call: Call, state: Int) {- currentCall = call- showOrClearNotification(call)+ if (call == currentCall) showOrClearNotification(call) SimCallBridge.onStateChanged(call, state)+ updateRinging() } override fun onDetailsChanged(call: Call, details: Call.Details) {- currentCall = call- showOrClearNotification(call)+ if (call == currentCall) showOrClearNotification(call)+ updateRinging() } } @@ -44,12 +54,12 @@ class CommunicateInCallService : InCallService() { override fun onCallAdded(call: Call) { super.onCallAdded(call)- currentCall?.unregisterCallback(callback) currentCall = call call.registerCallback(callback) showOrClearNotification(call) val number = call.details.handle?.schemeSpecificPart.orEmpty() SimCallBridge.onCallAdded(this, call, number, callerLabel(number))+ updateRinging() // Ringing must surface the screen, not just a notification: bring the app forward so the // InAppCallOverlay shows the incoming call with answer / decline. if (call.details.state == Call.STATE_RINGING) bringCallScreenForward()@@ -61,9 +71,42 @@ class CommunicateInCallService : InCallService() { if (wasTracked) currentCall = null clearNotification() SimCallBridge.onCallRemoved(call)+ updateRinging(removed = call) super.onCallRemoved(call) } + /** Volume or power pressed while ringing: Telecom asks the ringing dialer to go quiet. */+ override fun onSilenceRinger() {+ super.onSilenceRinger()+ ringController.silence()+ }++ override fun onDestroy() {+ ringController.release()+ LiveCalls.simCallLive = false+ super.onDestroy()+ }++ /** Re-derive ringing from every leg Telecom holds ([removed] may still be listed mid-removal). */+ private fun updateRinging(removed: Call? = null) {+ val legs = calls.filter { it != removed }.map { it.toSimLeg() }+ LiveCalls.simCallLive = legs.any { it.state == SimLegState.Live }+ ringController.onCallsChanged(legs)+ }++ private fun Call.toSimLeg(): SimLeg {+ val callDetails = details+ // Telecom puts a call-screening service's silence request in the intent extras.+ val silentRingingRequested = listOfNotNull(callDetails.intentExtras, callDetails.extras)+ .any { it.getBoolean(Call.EXTRA_SILENT_RINGING_REQUESTED) }+ return SimLeg(+ key = this,+ state = simLegState(callDetails.state),+ number = callDetails.handle?.schemeSpecificPart?.takeIf { it.isNotBlank() },+ silentRingingRequested = silentRingingRequested,+ )+ }+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { ACTION_ANSWER -> currentCall?.answer(VideoProfile.STATE_AUDIO_ONLY)@@ -108,9 +151,9 @@ class CommunicateInCallService : InCallService() { description = getString(R.string.regular_call_channel_desc), ) { lockscreenVisibility = Notification.VISIBILITY_PUBLIC- // Telecom (the system phone stack) owns ringing audio for carrier calls; this- // notification is only the answer/decline surface, so it stays silent and never- // re-alerts — otherwise its ding would double up with the system ringtone.+ // CallRinger owns ringing audio for carrier calls (IN_CALL_SERVICE_RINGING turns+ // Telecom's off); this notification is only the answer/decline surface, so it stays+ // silent and never re-alerts — otherwise its ding would double up with the ringtone. setSound(null, null) enableVibration(false) }@@ -167,7 +210,7 @@ class CommunicateInCallService : InCallService() { .setOngoing(true) .setAutoCancel(false) .setContentIntent(activityIntent())- .setFullScreenIntent(fullScreenIntent(), true)+ .setCallFullScreenIntent(this, fullScreenIntent()) .build() val nm = getSystemService(NotificationManager::class.java) ?: return nm.notify(NOTIFICATION_ID, notification)@@ -175,7 +218,7 @@ class CommunicateInCallService : InCallService() { private fun fullScreenIntent(): PendingIntent = PendingIntent.getActivity( this,- 4,+ FULL_SCREEN_REQUEST_CODE, Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) },@@ -224,6 +267,7 @@ class CommunicateInCallService : InCallService() { private const val ACTION_DECLINE = "com.vayunmathur.communicate.regularcall.DECLINE" private const val ACTION_DISCONNECT = "com.vayunmathur.communicate.regularcall.DISCONNECT" private const val DISCONNECT_REQUEST_CODE = 3+ private const val FULL_SCREEN_REQUEST_CODE = 4 private var currentCall: Call? = null private var lookedUpNumber: String? = null
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.ktindex 08beeb1897..89d334928f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt@@ -13,7 +13,10 @@ import androidx.core.content.ContextCompat import com.vayunmathur.communicate.MainActivity import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.googlevoice.call.CallPhase+import com.vayunmathur.communicate.data.googlevoice.call.CallState import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import com.vayunmathur.communicate.domain.dialableNumberOrNull+import com.vayunmathur.communicate.notifications.setCallFullScreenIntent import com.vayunmathur.library.util.deleteNotificationChannel import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.CoroutineScope@@ -61,11 +64,7 @@ class GoogleVoiceCallForegroundService : Service() { private fun startForegroundWithNotification() { ensureChannels() val state = GoogleVoiceCallManager.state.value- if (state.phase == CallPhase.Incoming) {- CallRinger.start(this)- } else {- CallRinger.stop()- }+ updateRinging(state) val contentIntent = callActivityIntent(0) val notification = if (state.phase == CallPhase.Incoming) { buildIncomingCallNotification(state.remoteNumber, contentIntent)@@ -80,6 +79,22 @@ class GoogleVoiceCallForegroundService : Service() { } } + private fun updateRinging(state: CallState) {+ if (state.phase == CallPhase.Incoming) {+ CallRinger.start(+ this,+ RingRequest(+ line = RingLine.GoogleVoice,+ callKey = state.remoteNumber,+ number = dialableNumberOrNull(state.remoteNumber),+ callWaiting = LiveCalls.otherThan(RingLine.GoogleVoice),+ ),+ )+ } else {+ CallRinger.stop(RingLine.GoogleVoice)+ }+ }+ private fun ensureChannels() { // Retired: the pre-ringer channel, whose system-kept sound would ding over the ringtone loop. deleteNotificationChannel(LEGACY_INCOMING_CHANNEL_ID)@@ -124,7 +139,7 @@ class GoogleVoiceCallForegroundService : Service() { .setOngoing(true) .setAutoCancel(false) .setContentIntent(contentIntent)- .setFullScreenIntent(callActivityIntent(1), true)+ .setCallFullScreenIntent(this, callActivityIntent(1)) .build() } @@ -170,7 +185,7 @@ class GoogleVoiceCallForegroundService : Service() { ) private fun stopSelfSafely() {- CallRinger.stop()+ CallRinger.stop(RingLine.GoogleVoice) androidx.core.app.ServiceCompat.stopForeground( this, androidx.core.app.ServiceCompat.STOP_FOREGROUND_REMOVE, )@@ -178,7 +193,7 @@ class GoogleVoiceCallForegroundService : Service() { } override fun onDestroy() {- CallRinger.stop()+ CallRinger.stop(RingLine.GoogleVoice) observeJob?.cancel() super.onDestroy() }
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.ktindex 263319ae8f..26c37983ff 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt@@ -40,6 +40,11 @@ class GoogleVoiceConnection : Connection(), CallConnection { destroy() } + /** Volume or power pressed while ringing: mute the ring, keep the call ringing on screen. */+ override fun onSilence() {+ CallRinger.silence(RingLine.GoogleVoice)+ }+ override fun onPlayDtmfTone(c: Char) { GoogleVoiceCallManager.sendDtmf(c.toString()) }
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.ktindex 410cfb1ee8..4b7af469b8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt@@ -14,8 +14,12 @@ import androidx.core.app.ServiceCompat import androidx.core.content.ContextCompat import com.vayunmathur.communicate.MainActivity import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.call.InAppCallPhase import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.call.InAppCallState+import com.vayunmathur.communicate.domain.dialableNumberOrNull+import com.vayunmathur.communicate.notifications.setCallFullScreenIntent import com.vayunmathur.library.util.deleteNotificationChannel import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.CoroutineScope@@ -63,11 +67,7 @@ class InAppCallForegroundService : Service() { private fun startForegroundWithNotification() { ensureChannels() val state = InAppCallRegistry.state.value- if (state.phase == InAppCallPhase.Incoming) {- CallRinger.start(this)- } else {- CallRinger.stop()- }+ updateRinging(state) val notification = if (state.phase == InAppCallPhase.Incoming) { buildIncomingCallNotification(state.peerName) } else {@@ -87,6 +87,27 @@ class InAppCallForegroundService : Service() { } } + /**+ * Ring while the WhatsApp/Signal call is incoming. The registry also mirrors SIM and Google Voice+ * calls, which ring from their own services, so only this service's lines ring here.+ */+ private fun updateRinging(state: InAppCallState) {+ val ownLine = state.line == CommunicateLine.WhatsApp || state.line == CommunicateLine.Signal+ if (state.phase == InAppCallPhase.Incoming && ownLine) {+ CallRinger.start(+ this,+ RingRequest(+ line = RingLine.InApp,+ callKey = "${state.line}:${state.peerId}",+ number = dialableNumberOrNull(state.peerId),+ callWaiting = LiveCalls.otherThan(RingLine.InApp),+ ),+ )+ } else {+ CallRinger.stop(RingLine.InApp)+ }+ }+ private fun ensureChannels() { // Retired: the pre-ringer channel, whose system-kept sound would ding over the ringtone loop. deleteNotificationChannel(LEGACY_INCOMING_CHANNEL_ID)@@ -129,7 +150,7 @@ class InAppCallForegroundService : Service() { .setVisibility(Notification.VISIBILITY_PUBLIC) .setOngoing(true) .setAutoCancel(false)- .setFullScreenIntent(callActivityIntent(1), true)+ .setCallFullScreenIntent(this, callActivityIntent(1)) .build() } @@ -170,13 +191,13 @@ class InAppCallForegroundService : Service() { ) private fun stopSelfSafely() {- CallRinger.stop()+ CallRinger.stop(RingLine.InApp) ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) stopSelf() } override fun onDestroy() {- CallRinger.stop()+ CallRinger.stop(RingLine.InApp) observeJob?.cancel() super.onDestroy() }
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.ktindex c716270fad..135d3c93ee 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt@@ -111,6 +111,11 @@ class InAppCallConnection : Connection(), InAppCallConnectionBridge { destroy() } + /** Volume or power pressed while ringing: mute the ring, keep the call ringing on screen. */+ override fun onSilence() {+ CallRinger.silence(RingLine.InApp)+ }+ /** The system mute button, as opposed to the in-app one. */ override fun onMuteStateChanged(isMuted: Boolean) { if (InAppCallRegistry.state.value.muted != isMuted) InAppCallRegistry.toggleMuted()
communicate/src/main/java/com/vayunmathur/communicate/telephony/LiveCalls.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/LiveCalls.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/LiveCalls.ktnew file mode 100644index 0000000000..0e92a0d19d--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/LiveCalls.kt@@ -0,0 +1,44 @@+package com.vayunmathur.communicate.telephony++import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.googlevoice.call.CallPhase+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager++/**+ * Which lines have a call up, so an incoming call on one line can tell it is call waiting behind a+ * call on another (a WhatsApp call arriving during a carrier call, and the reverse).+ *+ * "Up" means connected or being placed — not ringing: two calls ringing at once is not call waiting.+ */+object LiveCalls {+ /** Whether a carrier leg is active, held or dialing; published by [CommunicateInCallService]. */+ @Volatile+ var simCallLive: Boolean = false+ internal set++ /** Whether a call on any line other than [line] is up. */+ fun otherThan(line: RingLine): Boolean =+ (line != RingLine.Sim && simCallLive) ||+ (line != RingLine.GoogleVoice && googleVoiceLive()) ||+ (line != RingLine.InApp && inAppLive())++ private fun googleVoiceLive(): Boolean = when (GoogleVoiceCallManager.state.value.phase) {+ CallPhase.Dialing, CallPhase.Ringing, CallPhase.Active -> true+ CallPhase.Idle, CallPhase.Incoming, CallPhase.Ended -> false+ }++ /**+ * A WhatsApp or Signal call that is up. The registry also mirrors SIM and Google Voice calls, which+ * the other two checks already cover.+ */+ private fun inAppLive(): Boolean {+ val state = InAppCallRegistry.state.value+ val line = state.line ?: return false+ if (line == CommunicateLine.Sim || line == CommunicateLine.GoogleVoice) return false+ return state.phase == InAppCallPhase.Outgoing ||+ state.phase == InAppCallPhase.Connecting ||+ state.phase == InAppCallPhase.Active+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/RingEnvironmentReader.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RingEnvironmentReader.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RingEnvironmentReader.ktnew file mode 100644index 0000000000..c116f4138e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RingEnvironmentReader.kt@@ -0,0 +1,131 @@+package com.vayunmathur.communicate.telephony++import android.app.NotificationManager+import android.content.Context+import android.media.AudioManager+import android.net.Uri+import android.os.Build+import android.provider.ContactsContract.PhoneLookup+import android.provider.Settings+import android.telecom.PhoneAccount+import com.vayunmathur.communicate.domain.DndCallers+import com.vayunmathur.communicate.domain.DndMode+import com.vayunmathur.communicate.domain.DndPolicy+import com.vayunmathur.communicate.domain.RingConditions+import com.vayunmathur.communicate.domain.RingerMode+import com.vayunmathur.communicate.domain.dndAllowsCall+import com.vayunmathur.library.log.Log++/**+ * What [CallRinger] read from the system for one incoming call.+ *+ * @property customRingtone the caller's contact ringtone (`CUSTOM_RINGTONE`), or null for the default.+ */+internal data class RingEnvironment(+ val conditions: RingConditions,+ val customRingtone: Uri?,+)++/**+ * Reads the ringer switch, ring volume, "vibrate for calls", Do Not Disturb and the caller's contact+ * for [CallRinger]. Every read degrades to the permissive default when the platform refuses it, so a+ * missing permission costs a feature (the contact ringtone) rather than the ring itself.+ */+internal object RingEnvironmentReader {+ private const val TAG = "RingEnvironment"++ /**+ * Android 13 retired `VIBRATE_WHEN_RINGING`: the ring vibration intensity (0 = off) is what the+ * "vibrate for calls" switch writes now, and what Telecom's `SystemSettingsUtil` reads.+ */+ private const val RING_VIBRATION_INTENSITY = "ring_vibration_intensity"++ private class CallerContact(val customRingtone: Uri?, val starred: Boolean)++ fun read(context: Context, request: RingRequest): RingEnvironment {+ val audio = context.getSystemService(AudioManager::class.java)+ val contact = request.number?.let { lookUpContact(context, it) }+ val conditions = RingConditions(+ ringerMode = ringerMode(audio),+ ringVolumeAudible = audio == null || audio.getStreamVolume(AudioManager.STREAM_RING) > 0,+ vibrateWhenRinging = vibrateWhenRinging(context),+ callerAllowedByDnd = callerAllowedByDnd(context, request.number, contact),+ otherCallLive = request.callWaiting,+ )+ return RingEnvironment(conditions, contact?.customRingtone)+ }++ private fun ringerMode(audio: AudioManager?): RingerMode = when (audio?.ringerMode) {+ AudioManager.RINGER_MODE_SILENT -> RingerMode.Silent+ AudioManager.RINGER_MODE_VIBRATE -> RingerMode.Vibrate+ else -> RingerMode.Normal+ }++ private fun vibrateWhenRinging(context: Context): Boolean {+ val resolver = context.contentResolver+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ runCatching { Settings.System.getInt(resolver, RING_VIBRATION_INTENSITY) }+ .getOrNull()+ ?.let { return it != 0 }+ }+ @Suppress("DEPRECATION")+ val legacyKey = Settings.System.VIBRATE_WHEN_RINGING+ // Unreadable either way: vibrate. On Android 13+ the ringtone-usage vibration is still+ // dropped by the system when the user turned ring vibration off.+ return runCatching { Settings.System.getInt(resolver, legacyKey) != 0 }.getOrDefault(true)+ }++ /**+ * The caller's contact row via `PhoneLookup`, for the custom ringtone and the starred flag. An+ * empty `CUSTOM_RINGTONE` means "default", as in Telephony's `CallerInfo`.+ */+ private fun lookUpContact(context: Context, number: String): CallerContact? = runCatching {+ val uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))+ val projection = arrayOf(PhoneLookup.CUSTOM_RINGTONE, PhoneLookup.STARRED)+ context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->+ if (!cursor.moveToFirst()) return@use null+ CallerContact(+ customRingtone = cursor.getString(0)?.takeIf { it.isNotBlank() }?.let(Uri::parse),+ starred = cursor.getInt(1) != 0,+ )+ }+ }.onFailure {+ Log.status(TAG, "contact lookup for the ringtone failed", it)+ }.getOrNull()++ /**+ * Do Not Disturb for this caller. With a number on Android 13+ the platform decides+ * (`matchesCallFilter`), which is the only check that knows repeat callers; otherwise the active+ * policy is applied to what the contact lookup found.+ */+ private fun callerAllowedByDnd(context: Context, number: String?, contact: CallerContact?): Boolean {+ val nm = context.getSystemService(NotificationManager::class.java) ?: return true+ if (number != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ runCatching { nm.matchesCallFilter(Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null)) }+ .onFailure { Log.status(TAG, "matchesCallFilter unavailable; applying the DND policy", it) }+ .getOrNull()+ ?.let { return it }+ }+ return dndAllowsCall(dndPolicy(nm), isContact = contact != null, isStarred = contact?.starred == true)+ }++ private fun dndPolicy(nm: NotificationManager): DndPolicy {+ val mode = when (nm.currentInterruptionFilter) {+ NotificationManager.INTERRUPTION_FILTER_PRIORITY -> DndMode.PriorityOnly+ NotificationManager.INTERRUPTION_FILTER_ALARMS -> DndMode.AlarmsOnly+ NotificationManager.INTERRUPTION_FILTER_NONE -> DndMode.TotalSilence+ else -> DndMode.Off+ }+ if (mode != DndMode.PriorityOnly) return DndPolicy(mode, callsAllowed = false, callers = DndCallers.None)+ val policy = runCatching { nm.notificationPolicy }.getOrNull()+ ?: return DndPolicy(mode, callsAllowed = false, callers = DndCallers.None)+ val callers = when (policy.priorityCallSenders) {+ NotificationManager.Policy.PRIORITY_SENDERS_ANY -> DndCallers.Anyone+ NotificationManager.Policy.PRIORITY_SENDERS_CONTACTS -> DndCallers.Contacts+ NotificationManager.Policy.PRIORITY_SENDERS_STARRED -> DndCallers.Starred+ else -> DndCallers.None+ }+ val callsAllowed = (policy.priorityCategories and NotificationManager.Policy.PRIORITY_CATEGORY_CALLS) != 0+ return DndPolicy(mode, callsAllowed, callers)+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/SimRingController.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/SimRingController.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/SimRingController.ktnew file mode 100644index 0000000000..51d9d09202--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/SimRingController.kt@@ -0,0 +1,99 @@+package com.vayunmathur.communicate.telephony++import android.telecom.Call++/** How a carrier call leg bears on ringing. */+enum class SimLegState {+ /** Ringing, so it should alert. */+ Ringing,++ /** Up or being set up (active, held, dialing), so a ringing leg beside it is call waiting. */+ Live,++ /** Anything else: new, screening, disconnecting, gone. */+ Other,+}++/** Classify a Telecom `Call.STATE_*`. Simulated ringing (after call-screening audio processing) rings too. */+fun simLegState(telecomState: Int): SimLegState = when (telecomState) {+ Call.STATE_RINGING, Call.STATE_SIMULATED_RINGING -> SimLegState.Ringing+ Call.STATE_ACTIVE, Call.STATE_HOLDING, Call.STATE_DIALING, Call.STATE_CONNECTING, Call.STATE_PULLING_CALL ->+ SimLegState.Live+ else -> SimLegState.Other+}++/**+ * One carrier call leg as [SimRingController] needs it.+ *+ * @property key identifies the leg (the Telecom `Call` itself in production).+ * @property silentRingingRequested a call-screening service asked Telecom to ring this call silently+ * (`Call.EXTRA_SILENT_RINGING_REQUESTED`), which a dialer that rings must honour.+ */+data class SimLeg(+ val key: Any,+ val state: SimLegState,+ val number: String?,+ val silentRingingRequested: Boolean = false,+)++/**+ * Starts and stops the ringer for carrier calls, from the full set of legs [CommunicateInCallService]+ * holds. Feed it every leg after any change (added, removed, state change); it works out the transition.+ *+ * Follows AOSP Telecom, whose `Ringer` this replaces once the dialer declares `IN_CALL_SERVICE_RINGING`:+ * - The ringing leg alerts per [com.vayunmathur.communicate.domain.ringPlan].+ * - A ringing leg while another leg (or another line's call, via [otherLineLive]) is up is call+ * waiting: the call-waiting tone instead of the ringtone.+ * - If the live call ends while the waiting leg still rings, the waiting leg switches to a full ring.+ * - Answer, reject, disconnect, or answering another call ends the ring.+ * - The volume/power key ([silence]) and call screening's silent-ringing request mute that leg for good.+ *+ * Pure state over an [IncomingRinger] so the transitions are unit-tested with fakes.+ */+class SimRingController(+ private val ringer: IncomingRinger,+ private val otherLineLive: () -> Boolean,+) {+ private var ringingKey: Any? = null+ private var ringingWaiting = false+ private var silencedKey: Any? = null++ fun onCallsChanged(legs: List<SimLeg>) {+ val ringing = legs.firstOrNull { it.state == SimLegState.Ringing }+ if (ringing == null) {+ silencedKey = null+ stopRinging()+ return+ }+ if (ringing.silentRingingRequested || ringing.key == silencedKey) {+ stopRinging()+ return+ }+ val waiting = legs.any { it.key != ringing.key && it.state == SimLegState.Live } || otherLineLive()+ if (ringing.key == ringingKey && waiting == ringingWaiting) return+ ringingKey = ringing.key+ ringingWaiting = waiting+ ringer.ring(RingRequest(RingLine.Sim, ringing.key, ringing.number, callWaiting = waiting))+ }++ /** The user pressed volume or power while ringing: mute it; the call keeps ringing on screen. */+ fun silence() {+ val key = ringingKey ?: return+ silencedKey = key+ stopRinging()+ }++ /** The service is going away; nothing may keep ringing after it. */+ fun release() {+ silencedKey = null+ ringingKey = null+ ringer.stop(RingLine.Sim)+ }++ private fun stopRinging() {+ if (ringingKey == null) return+ ringingKey = null+ ringingWaiting = false+ ringer.stop(RingLine.Sim)+ }+}
communicate/src/test/java/com/vayunmathur/communicate/domain/RingPolicyTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/domain/RingPolicyTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/domain/RingPolicyTest.ktnew file mode 100644index 0000000000..6cc9be0bb7--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/domain/RingPolicyTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.communicate.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class RingPolicyTest {+ private fun conditions(+ ringerMode: RingerMode = RingerMode.Normal,+ ringVolumeAudible: Boolean = true,+ vibrateWhenRinging: Boolean = true,+ callerAllowedByDnd: Boolean = true,+ otherCallLive: Boolean = false,+ ) = RingConditions(ringerMode, ringVolumeAudible, vibrateWhenRinging, callerAllowedByDnd, otherCallLive)++ @Test+ fun `normal mode rings and vibrates when vibrate for calls is on`() {+ assertEquals(+ RingPlan(ringtone = true, vibrate = true, callWaitingTone = false),+ ringPlan(conditions()),+ )+ }++ @Test+ fun `normal mode rings without vibration when vibrate for calls is off`() {+ assertEquals(+ RingPlan(ringtone = true, vibrate = false, callWaitingTone = false),+ ringPlan(conditions(vibrateWhenRinging = false)),+ )+ }++ @Test+ fun `normal mode at zero ring volume only vibrates per the setting`() {+ assertEquals(RingPlan.VibrateOnly, ringPlan(conditions(ringVolumeAudible = false)))+ assertEquals(RingPlan.Silent, ringPlan(conditions(ringVolumeAudible = false, vibrateWhenRinging = false)))+ }++ @Test+ fun `vibrate mode vibrates only, whatever the vibrate-for-calls setting`() {+ assertEquals(RingPlan.VibrateOnly, ringPlan(conditions(ringerMode = RingerMode.Vibrate)))+ assertEquals(+ RingPlan.VibrateOnly,+ ringPlan(conditions(ringerMode = RingerMode.Vibrate, vibrateWhenRinging = false)),+ )+ }++ @Test+ fun `silent mode plays nothing and does not vibrate`() {+ val plan = ringPlan(conditions(ringerMode = RingerMode.Silent))+ assertEquals(RingPlan.Silent, plan)+ assertTrue(plan.isSilent)+ }++ @Test+ fun `a caller do not disturb filters out gets nothing in any mode`() {+ RingerMode.entries.forEach { mode ->+ assertEquals(RingPlan.Silent, ringPlan(conditions(ringerMode = mode, callerAllowedByDnd = false)))+ }+ assertEquals(RingPlan.Silent, ringPlan(conditions(callerAllowedByDnd = false, otherCallLive = true)))+ }++ @Test+ fun `call waiting plays only the call-waiting tone`() {+ assertEquals(RingPlan.CallWaiting, ringPlan(conditions(otherCallLive = true)))+ assertFalse(RingPlan.CallWaiting.isSilent)+ }++ @Test+ fun `call waiting tone ignores the ringer switch because it is in-call audio`() {+ assertEquals(+ RingPlan.CallWaiting,+ ringPlan(conditions(ringerMode = RingerMode.Silent, otherCallLive = true)),+ )+ assertEquals(+ RingPlan.CallWaiting,+ ringPlan(conditions(ringerMode = RingerMode.Vibrate, otherCallLive = true)),+ )+ }++ private val priorityAnyone = DndPolicy(DndMode.PriorityOnly, callsAllowed = true, callers = DndCallers.Anyone)++ @Test+ fun `dnd off lets everyone through`() {+ val off = DndPolicy(DndMode.Off, callsAllowed = false, callers = DndCallers.None)+ assertTrue(dndAllowsCall(off, isContact = false, isStarred = false))+ }++ @Test+ fun `alarms-only and total silence block even starred contacts`() {+ listOf(DndMode.AlarmsOnly, DndMode.TotalSilence).forEach { mode ->+ val policy = priorityAnyone.copy(mode = mode)+ assertFalse(dndAllowsCall(policy, isContact = true, isStarred = true))+ }+ }++ @Test+ fun `priority mode without calls blocks everyone`() {+ val policy = priorityAnyone.copy(callsAllowed = false)+ assertFalse(dndAllowsCall(policy, isContact = true, isStarred = true))+ }++ @Test+ fun `priority mode applies the allowed callers`() {+ assertTrue(dndAllowsCall(priorityAnyone, isContact = false, isStarred = false))++ val contacts = priorityAnyone.copy(callers = DndCallers.Contacts)+ assertTrue(dndAllowsCall(contacts, isContact = true, isStarred = false))+ assertFalse(dndAllowsCall(contacts, isContact = false, isStarred = false))++ val starred = priorityAnyone.copy(callers = DndCallers.Starred)+ assertTrue(dndAllowsCall(starred, isContact = true, isStarred = true))+ assertFalse(dndAllowsCall(starred, isContact = true, isStarred = false))++ val none = priorityAnyone.copy(callers = DndCallers.None)+ assertFalse(dndAllowsCall(none, isContact = true, isStarred = true))+ }++ @Test+ fun `dialable numbers pass through with formatting stripped`() {+ assertEquals("+15551234567", dialableNumberOrNull("+15551234567"))+ assertEquals("5551234567", dialableNumberOrNull("(555) 123-4567"))+ assertEquals("15551234567", dialableNumberOrNull("[email protected]"))+ assertEquals("15551234567", dialableNumberOrNull("15551234567:[email protected]"))+ }++ @Test+ fun `peers without a phone number have no dialable number`() {+ assertNull(dialableNumberOrNull("123456789012345@lid"))+ assertNull(dialableNumberOrNull("3f2c1d0e-8b7a-4c6d-9e5f-1a2b3c4d5e6f"))+ assertNull(dialableNumberOrNull(""))+ assertNull(dialableNumberOrNull("Anonymous"))+ }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.ktindex 4ecab2f4bb..43151fbaa0 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt@@ -1,7 +1,10 @@ package com.vayunmathur.communicate.telephony +import android.media.AudioManager import android.os.Vibrator import androidx.test.core.app.ApplicationProvider+import kotlin.test.AfterTest+import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue@@ -12,9 +15,10 @@ import org.robolectric.Shadows.shadowOf /** * Slice-4 coverage for the shared call ringer ([CallRinger]). *- * Robolectric with the media/vibration shadows: asserts start is idempotent,- * stop always releases, and a second start after stop re-rings — the contract- * that keeps answer/decline from every surface silencing the same loop twice.+ * Robolectric with the media/vibration shadows: asserts start is idempotent per call, stop always+ * releases and only for its own line, a second start after stop re-rings, and the ringer switch is+ * honoured (#856: the ringer used to vibrate even in silent mode). The pure decision table lives in+ * `RingPolicyTest`; this checks the platform side follows it. */ @RunWith(RobolectricTestRunner::class) class CallRingerSlice4Test {@@ -22,46 +26,101 @@ class CallRingerSlice4Test { private val context: android.content.Context get() = ApplicationProvider.getApplicationContext() + private val vibrator: Vibrator+ get() = context.getSystemService(Vibrator::class.java)!!++ private val audio: AudioManager+ get() = context.getSystemService(AudioManager::class.java)!!++ private fun request(key: String = "peer", line: RingLine = RingLine.InApp, waiting: Boolean = false) =+ RingRequest(line, key, number = null, callWaiting = waiting)++ @BeforeTest+ fun reset() {+ RingLine.entries.forEach(CallRinger::stop)+ audio.ringerMode = AudioManager.RINGER_MODE_NORMAL+ }++ @AfterTest+ fun tearDown() {+ RingLine.entries.forEach(CallRinger::stop)+ }+ @Test fun `start vibrates and stop cancels`() {- CallRinger.stop()- val vibrator = context.getSystemService(Vibrator::class.java)!!- CallRinger.start(context)+ CallRinger.start(context, request()) assertTrue(shadowOf(vibrator).isVibrating)- CallRinger.stop()+ CallRinger.stop(RingLine.InApp) assertFalse(shadowOf(vibrator).isVibrating) } @Test- fun `second start while ringing keeps the same loop`() {- CallRinger.stop()- CallRinger.start(context)- CallRinger.start(context)- CallRinger.stop()+ fun `second start for the same call keeps the same loop`() {+ CallRinger.start(context, request())+ CallRinger.start(context, request())+ assertTrue(shadowOf(vibrator).isVibrating)+ CallRinger.stop(RingLine.InApp)+ assertFalse(shadowOf(vibrator).isVibrating) } @Test fun `stop without start is safe`() {- CallRinger.stop()- CallRinger.stop()+ CallRinger.stop(RingLine.InApp)+ CallRinger.stop(RingLine.InApp) } @Test fun `start after stop rings again`() {- CallRinger.stop()- CallRinger.start(context)- CallRinger.stop()- CallRinger.start(context)- CallRinger.stop()+ CallRinger.start(context, request())+ CallRinger.stop(RingLine.InApp)+ CallRinger.start(context, request())+ assertTrue(shadowOf(vibrator).isVibrating)+ }++ @Test+ fun `another line's stop leaves the ring alone`() {+ CallRinger.start(context, request(line = RingLine.Sim))+ CallRinger.stop(RingLine.InApp)+ CallRinger.stop(RingLine.GoogleVoice)+ assertTrue(shadowOf(vibrator).isVibrating)+ CallRinger.stop(RingLine.Sim)+ assertFalse(shadowOf(vibrator).isVibrating) } @Test- fun `media player state follows the ringer`() {- CallRinger.stop()- // The ringer owns exactly one MediaPlayer generation at a time; a stale- // prepared callback must not restart audio after stop (guarded by- // identity in CallRinger.startSound — exercised here via start/stop).- CallRinger.start(context)- CallRinger.stop()+ fun `silent mode neither rings nor vibrates`() {+ audio.ringerMode = AudioManager.RINGER_MODE_SILENT+ CallRinger.start(context, request())+ assertFalse(shadowOf(vibrator).isVibrating)+ }++ @Test+ fun `vibrate mode vibrates`() {+ audio.ringerMode = AudioManager.RINGER_MODE_VIBRATE+ CallRinger.start(context, request())+ assertTrue(shadowOf(vibrator).isVibrating)+ }++ @Test+ fun `call waiting does not vibrate`() {+ CallRinger.start(context, request(waiting = true))+ assertFalse(shadowOf(vibrator).isVibrating)+ }++ @Test+ fun `silence mutes and a repeat start for the same call stays muted`() {+ CallRinger.start(context, request())+ CallRinger.silence(RingLine.InApp)+ assertFalse(shadowOf(vibrator).isVibrating)+ CallRinger.start(context, request())+ assertFalse(shadowOf(vibrator).isVibrating)+ }++ @Test+ fun `a different call after silence rings`() {+ CallRinger.start(context, request("first"))+ CallRinger.silence(RingLine.InApp)+ CallRinger.start(context, request("second"))+ assertTrue(shadowOf(vibrator).isVibrating) } }
communicate/src/test/java/com/vayunmathur/communicate/telephony/SimRingControllerTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimRingControllerTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimRingControllerTest.ktnew file mode 100644index 0000000000..775533848d--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimRingControllerTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.communicate.telephony++import android.telecom.Call+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SimRingControllerTest {+ /** Records what the controller asked of the ringer, in order. */+ private class FakeRinger : IncomingRinger {+ val events = mutableListOf<String>()+ val requests = mutableListOf<RingRequest>()++ override fun ring(request: RingRequest) {+ requests += request+ events += if (request.callWaiting) "waiting:${request.callKey}" else "ring:${request.callKey}"+ }++ override fun stop(line: RingLine) {+ events += "stop:$line"+ }+ }++ private val ringer = FakeRinger()+ private var otherLineLive = false+ private val controller = SimRingController(ringer) { otherLineLive }++ private fun ringing(key: String, number: String? = "+15551234567") = SimLeg(key, SimLegState.Ringing, number)++ private fun live(key: String) = SimLeg(key, SimLegState.Live, "+15550000000")++ private fun other(key: String) = SimLeg(key, SimLegState.Other, null)++ @Test+ fun `an incoming call rings once however often it is reported`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.onCallsChanged(listOf(ringing("a")))+ controller.onCallsChanged(listOf(ringing("a")))++ assertEquals(listOf("ring:a"), ringer.events)+ val request = ringer.requests.single()+ assertEquals(RingLine.Sim, request.line)+ assertEquals("+15551234567", request.number)+ }++ @Test+ fun `answering stops the ring`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.onCallsChanged(listOf(live("a")))++ assertEquals(listOf("ring:a", "stop:Sim"), ringer.events)+ }++ @Test+ fun `rejecting or a remote hangup stops the ring`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.onCallsChanged(listOf(other("a")))+ controller.onCallsChanged(emptyList())++ assertEquals(listOf("ring:a", "stop:Sim"), ringer.events)+ }++ @Test+ fun `nothing stops when nothing was ringing`() {+ controller.onCallsChanged(listOf(live("a")))+ controller.onCallsChanged(emptyList())++ assertTrue(ringer.events.isEmpty())+ }++ @Test+ fun `an outgoing call never rings`() {+ controller.onCallsChanged(listOf(other("a")))+ controller.onCallsChanged(listOf(live("a")))++ assertTrue(ringer.events.isEmpty())+ }++ @Test+ fun `a second call during an active call gets the call-waiting tone`() {+ controller.onCallsChanged(listOf(live("a")))+ controller.onCallsChanged(listOf(live("a"), ringing("b")))++ assertEquals(listOf("waiting:b"), ringer.events)+ }++ @Test+ fun `answering the waiting call stops the tone`() {+ controller.onCallsChanged(listOf(live("a"), ringing("b")))+ controller.onCallsChanged(listOf(live("a"), live("b")))++ assertEquals(listOf("waiting:b", "stop:Sim"), ringer.events)+ }++ @Test+ fun `declining the waiting call stops the tone and leaves the active call alone`() {+ controller.onCallsChanged(listOf(live("a"), ringing("b")))+ controller.onCallsChanged(listOf(live("a")))++ assertEquals(listOf("waiting:b", "stop:Sim"), ringer.events)+ }++ @Test+ fun `the waiting call switches to a full ring when the active call ends`() {+ controller.onCallsChanged(listOf(live("a"), ringing("b")))+ controller.onCallsChanged(listOf(ringing("b")))++ assertEquals(listOf("waiting:b", "ring:b"), ringer.events)+ }++ @Test+ fun `a call on another line makes a carrier call waiting`() {+ otherLineLive = true+ controller.onCallsChanged(listOf(ringing("a")))++ assertEquals(listOf("waiting:a"), ringer.events)+ }++ @Test+ fun `silencing stops the ring and later reports of that call stay silent`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.silence()+ controller.onCallsChanged(listOf(ringing("a")))++ assertEquals(listOf("ring:a", "stop:Sim"), ringer.events)+ }++ @Test+ fun `a new call after a silenced one rings again`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.silence()+ controller.onCallsChanged(emptyList())+ controller.onCallsChanged(listOf(ringing("b")))++ assertEquals(listOf("ring:a", "stop:Sim", "ring:b"), ringer.events)+ }++ @Test+ fun `silence with nothing ringing does nothing`() {+ controller.silence()++ assertTrue(ringer.events.isEmpty())+ }++ @Test+ fun `call screening's silent-ringing request is honoured`() {+ controller.onCallsChanged(listOf(ringing("a").copy(silentRingingRequested = true)))++ assertTrue(ringer.events.isEmpty())+ }++ @Test+ fun `release always stops the ringer`() {+ controller.onCallsChanged(listOf(ringing("a")))+ controller.release()++ assertEquals(listOf("ring:a", "stop:Sim"), ringer.events)+ }++ @Test+ fun `telecom states map to ringing, live and other`() {+ assertEquals(SimLegState.Ringing, simLegState(Call.STATE_RINGING))+ assertEquals(SimLegState.Ringing, simLegState(Call.STATE_SIMULATED_RINGING))+ listOf(+ Call.STATE_ACTIVE,+ Call.STATE_HOLDING,+ Call.STATE_DIALING,+ Call.STATE_CONNECTING,+ Call.STATE_PULLING_CALL,+ ).forEach { assertEquals(SimLegState.Live, simLegState(it)) }+ listOf(+ Call.STATE_NEW,+ Call.STATE_AUDIO_PROCESSING,+ Call.STATE_DISCONNECTING,+ Call.STATE_DISCONNECTED,+ Call.STATE_SELECT_PHONE_ACCOUNT,+ ).forEach { assertEquals(SimLegState.Other, simLegState(it)) }+ }+}