feat(android): create VoipCallService with FOREGROUND_SERVICE_MICROPHONE#7199
Conversation
New `VoipCallService` extends `Service` and runs as a foreground service with `foregroundServiceType="microphone"`. Keeps VoIP audio calls alive when the app moves to the background (Android terminates background processes without a foreground service). - Service starts via `VoipCallService.startService(context, callId)` with ACTION_START - Service stops via `VoipCallService.stopService(context)` with ACTION_STOP - Starts with `ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE` on API 29+ - Creates low-priority notification channel and ongoing notification - Manifest declares service with `foregroundServiceType="microphone"` Fixes: C2 (missing VoipCallService with FOREGROUND_SERVICE_MICROPHONE)
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
WalkthroughAdds a new Android foreground service, Changes
Sequence Diagram(s)sequenceDiagram
participant App as App / Caller
participant Service as VoipCallService
participant Notif as NotificationManager
participant OS as Android OS
participant Main as MainActivity
participant User as User
App->>Service: startService(context, callId)
Service->>Service: if isRunning -> ignore
alt not running
Service->>Notif: createNotificationChannel() (Android O+)
Service->>Notif: build ongoing Notification (PendingIntent -> Main)
Service->>OS: startForeground(notification) [FOREGROUND_SERVICE_TYPE_MICROPHONE on Q+]
Service->>Service: isRunning = true
end
User->>Main: tap notification (PendingIntent)
App->>Service: stopService(context)
Service->>Service: onStartCommand(ACTION_STOP) -> stopSelf()
Service->>OS: stopForeground/stopSelf()
Service->>Service: onDestroy() -> isRunning = false
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (6)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Code Review — PR #7199Files Reviewed: [LOW]
|
| Criterion | Status | Notes |
|---|---|---|
VoipCallService.kt exists and compiles |
✅ | BUILD SUCCESSFUL |
Manifest declares service with foregroundServiceType="microphone" |
✅ | Line 152-156 |
Manifest declares FOREGROUND_SERVICE_MICROPHONE permission |
✅ | Implied by foregroundServiceType attribute (no separate permission needed on API 34-) |
| Service starts in foreground with notification | ✅ | startForegroundWithNotification() with ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE on API 29+ |
Service stops via stopSelf() correctly |
✅ | ACTION_STOP path calls stopSelf() at line 79 |
Positive Observations
- Clean intent-based control.
ACTION_START/ACTION_STOPpattern is simple, testable, and avoids static state. - API-level guard correct.
ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONEonly used on API 29+ (Android 10), with plainstartForegroundon earlier versions. - Notification channel properly scoped.
IMPORTANCE_LOW+setShowBadge(false)is correct for a persistent service notification that shouldn't interrupt the user. - PendingIntent flags correct. Uses
FLAG_IMMUTABLEon API 31+ with fallback to 0. - Matches iOS CallKit pattern. Parity with how CallKit keeps the VoIP call alive on iOS.
Verdict
LGTM — All 5 acceptance criteria satisfied. Both LOW observations are informational only and don't block the PR. The isRunning guard issue is LOW because in practice, startForeground is idempotent even if the flag isn't reset on recreation.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@android/app/src/main/java/chat/rocket/reactnative/voip/VoipCallService.kt`:
- Around line 73-74: The code logs a potentially sensitive call identifier when
starting the service; in VoipCallService replace the Log.d(TAG, "Starting
VoipCallService for callId: $callId") with a generic lifecycle message that
omits the callId (e.g., "Starting VoipCallService"); keep retrieving
EXTRA_CALL_ID into callId if needed for logic but do not include it in any logs
or exceptions, and make the same change for the other occurrence that logs
callId (the Log.d/Log.i call around the second usage noted at the other
occurrence).
- Around line 50-56: The stopService function in VoipCallService builds an
Intent with ACTION_STOP and incorrectly calls context.startService(intent);
change this to call context.stopService(intent) so the service is stopped via
Context.stopService(), avoiding background-start IllegalStateException on
Android 8+; update the call inside fun stopService(context:
android.content.Context) to use context.stopService(intent) while keeping the
Intent construction with ACTION_STOP and the VoipCallService::class.java target.
- Around line 65-85: The onStartCommand implementation in VoipCallService should
not return START_STICKY because the service cannot recover call state from a
null intent; update the ACTION_START branch return to START_NOT_STICKY so the OS
won't restart the service expecting to restore an active WebRTC call, and change
unconditional stopSelf() calls to stopSelf(startId) to use the precise lifecycle
token; specifically modify VoipCallService.onStartCommand (handling ACTION_STOP
and ACTION_START), keep the existing isRunning and
startForegroundWithNotification(callId) logic, but replace returns of
START_STICKY with START_NOT_STICKY and replace stopSelf() with
stopSelf(startId).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 849f03af-c8b1-4ac9-bb62-a4f316ce8da8
📒 Files selected for processing (2)
android/app/src/main/AndroidManifest.xmlandroid/app/src/main/java/chat/rocket/reactnative/voip/VoipCallService.kt
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: ESLint and Test / run-eslint-and-test
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
Repo: RocketChat/Rocket.Chat.ReactNative PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-04-07T17:49:17.538Z
Learning: Applies to app/lib/services/voip/**/*.{ts,tsx} : Implement VoIP with WebRTC peer-to-peer audio calls in app/lib/services/voip/ using Zustand stores instead of Redux, with native CallKit (iOS) and Telecom (Android) integration; keep VoIP and VideoConf separate
📚 Learning: 2026-04-07T17:49:17.538Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat.ReactNative PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-04-07T17:49:17.538Z
Learning: Applies to app/lib/services/voip/**/*.{ts,tsx} : Implement VoIP with WebRTC peer-to-peer audio calls in app/lib/services/voip/ using Zustand stores instead of Redux, with native CallKit (iOS) and Telecom (Android) integration; keep VoIP and VideoConf separate
Applied to files:
android/app/src/main/AndroidManifest.xmlandroid/app/src/main/java/chat/rocket/reactnative/voip/VoipCallService.kt
🔇 Additional comments (1)
android/app/src/main/AndroidManifest.xml (1)
150-155: LGTM — service declaration matches the foreground microphone use case.The service is non-exported and declares the expected
microphoneforeground service type.
Code Review — Opus-Level Architecture ReviewPR: #7199 — feat(android): create VoipCallService with FOREGROUND_SERVICE_TYPE_MICROPHONE Stage 1 — Spec Compliance
All five acceptance criteria are satisfied. Stage 2 — Code Quality[HIGH] Race condition in
|
- Companion stopService() now calls Context.stopService() instead of startService(): calling startService() from a background context on Android 8+ throws IllegalStateException. stopService() with the same Intent is always safe and also respects the service component. - onStartCommand now returns START_NOT_STICKY for ACTION_START so the system does not redeliver a null Intent after process death (which could not recover the WebRTC call state anyway). - ACTION_STOP uses stopSelf(startId) so only the matching start token is released; the unknown-action branch also calls stopSelf(startId) before returning to prevent leaked start counts.
Follow-up review — partially dismissing the prior Opus reviewRe: previous review. Re-evaluated each finding against the current tree and Android platform guarantees. Summary: one valid minor, one obsolete, one overstated. [HIGH]
|
…/Decline (#7215) * merge feat.voip-lib * feat(voip): enhance call handling with UUID mapping and event listeners * Base call UI * feat(voip): integrate Zustand for call state management and enhance CallView UI * feat(voip): add simulateCall function for mock call handling in UI development * refactor(CallView): update button handlers and improve UI responsiveness * Add pause-shape-unfilled icon * Base CallHeader * toggleFocus * collapse buttons * Header components * Hide header when no call * Timer * Add use memo * Add voice call item on sidebar * cleanup * Temp use @rocket.chat/media-signaling from .tgz * cleanup * Check module and permissions to enable voip * Refactor stop method to use optional chaining for media signal listeners * voip push first test * Add VoIP call handling with pending call management - Implemented VoIP push notification handling in index.js, including storing call info for later processing. - Added CallKeep event handlers for answering and ending calls from a cold start. - Introduced a new CallIdUUID module to convert call IDs to deterministic UUIDs for compatibility with CallKit. - Created a pending call store to manage incoming calls when the app is not fully initialized. - Updated deep linking actions to include VoIP call handling. - Enhanced MediaSessionInstance to process pending calls and manage call states effectively. * Remove pending store and create getInitialEvents on app/index * Attempt to make iOS calls work from cold state * lint and format * Patch callkeep ios * Temp send iOS voip push token on gcm * Temp fix require cycle * chore: format code and fix lint issues [skip ci] * CallIDUUID module on android and voip push * Add setCallUUID on useCallStore to persist calls accepted on native Android * remove callkeep from notification * Android Incoming Call UI POC * Refactor VoIP handling: Migrate VoIP-related classes to a new package structure, removing deprecated modules and consolidating functionality. Update imports in MainApplication and NotificationIntentHandler to reflect changes. This cleanup enhances code organization and prepares for future VoIP feature enhancements. * Remove VoipForegroundService * cleanup and use caller instead of callerName * Cleanup and make iOS build again * Refactor VoIP handling: Remove unused event emissions for call answered and declined, switch from SharedPreferences to in-memory storage for pending VoIP call data, and update method signatures for better clarity. This cleanup enhances performance and prepares for future VoIP feature improvements. * Refactor VoIP handling: Introduce a new VoipPayload class to encapsulate call data, streamline notification processing, and enhance method signatures across the VoIP module. This update improves code clarity and prepares for future feature enhancements. * Migrate react-native-voip-push-notifications to VoipModule * Refactor VoIP module: Update package structure by moving VoipTurboPackage to the main package and removing the obsolete NativeVoipSpec class. Adjust imports in MainApplication and VoipModule to reflect these changes, enhancing code organization and maintainability. * Unify emitters * Move CallKeep listeners from MediaSessionInstance to getInitialEvents * Clear callkeep on endcall * Unify getInitialEvents logic * getInitialEvents -> MediaCallEvents * chore: format code and fix lint issues [skip ci] * feat(Android): Add full screen incoming call (#6977) * feat: Update call UI (#6990) * feat: Handle audio routing, e.g., Bluetooth headset vs. internal speaker switching (#6992) * fix: empty space when not on call (#6993) * feat: Dialpad (#7000) * action: organized translations * feat: start call (#7024) * chore: format code and fix lint issues * feat: Pre flight (#7038) * action: organized translations * feat: Receive voip push notifications from backend (#7045) * feat: Refactor media session handling and improve disconnect logic (#7065) * feat: Control incoming call from native (#7066) * feat: Voice message blocks (#7057) * feat: native accept success event (#7068) * feat(voip): call waiting, busy detection, and videoconf blocking (#7077) * action: organized translations * feat(voip): tap-to-hide call controls with animations (#7078) * feat(voip): navigate to call DM from message button and header (#7082) * feat(voip): tablet and landscape layout (#7110) * chore: develop into feat.voip-lib-new (RN 81 + Expo 54 + reanimated 4 + true-sheet + iOS 26) (#7114) * chore: format code and fix lint issues * feat(voip): android landscape layout for IncomingCallActivity (#7116) * Update agents files * feat(voip): Support a11y (#7106) * Fix content cutting on iOS on some edge cases * pods * Ignore .worktrees on jest * chore: Merge develop into feat.voip-lib-new (#7129) * fix(voip): show CallKit UI when call is active in background (#7128) * chore: Update media-signaling to 0.2.0 (#7153) * feat(voip): migrate iOS accept/reject from DDP to REST (#7124) * Fix icons * feat(voip): migrate Android accept/reject from DDP to REST (#7127) * test(voip): integration tests for CallView pipeline (#7161) * feat(voip): display video conf provider as subtitle (#7160) * fix(voip): CallView button grid and correct landscape/dialpad layouts (#7164) * fix(voip): prevent stale MMKV cache on Android first-install accept MMKVKeyManager.initialize ran in MainApplication.onCreate before the JS engine started and opened the default MMKV file via the Tencent 1.2 JAR when it was still empty. Tencent caches instances per-ID in a singleton registry, so that empty-state view was held for the rest of the process. JS later wrote credentials through react-native-mmkv (MMKV Core 2.0), which has its own separate registry. When a VoIP push arrived, Ejson.getMMKV() got the cached empty Tencent instance and reported "No userId found in MMKV for server". Closing and reopening the app cleared the cache, which is why only the very first call after install failed. Drop the open/verify block — the encryption key is already cached from SecureKeystore, so no MMKV handle is needed here. The first Tencent instance is now created inside Ejson.getMMKV() after JS has written, so it scans the file fresh. * fix(voip): prevent duplicate ringtone on Android incoming call (#7158) * fix(voip): set explicit snaps for NewMediaCall bottom sheet (#7165) * Update app/lib/services/voip/MediaSessionStore.ts Co-authored-by: Pierre Lehnen <55164754+pierre-lehnen-rc@users.noreply.github.com> * fix: make startVoipFork reactive to permissions-changed (#7151) * fix(android): remove MediaProjectionService from merged manifest (#7190) * fix(voip): Phone account creation (#7170) * feat: add Enable Mobile Ringing toggle in user preferences (#7155) * fix(voip): ship blockers for PushKit, licensing, outbound calls, push tokens (#7167) * fix(android): Play Store mic discoverability, safer FCM logs, avatar auth via headers (#7171) * fix(ios): serialize VoipService bridge statics (#7169) * fix(voip): Android DDP thread safety and VoipPayload bundle parity (#7168) * chore(voip): dead-code and hygiene sweep (#7174) * refactor(voip): decouple navigateToCallRoom from Redux and backfill REST/connect tests (#7176) * test(voip): tighten ringing endCall assertion and add VideoConf VoIP-lock saga coverage (#7177) * fix(ios): harden VoIP DDP WebSocket client on receive failures and TLS (#7173) * refactor(voip): MediaCallEvents Redux adapters and resetVoipState (#7178) * refactor(voip): decouple peer autocomplete from Redux; simplify NewMediaCall (#7175) * fix(ios): add NS_SWIFT_NAME to Challenge.runChallenge for Swift 6.2 compatibility Swift 6.2 (Xcode 26.x / macos-26 runner) auto-renames the Objective-C method runChallenge:didReceiveChallenge:completionHandler: to run(_:didReceive:completionHandler:) when imported into Swift. Add NS_SWIFT_NAME to explicitly pin the Swift import name, preventing the compiler from applying its heuristics. This keeps the existing Swift call site in DDPClient.swift working without changes. * fix(ios): cancel old URLSession/webSocketTask before reconnecting in DDPClient.connect (#7197) * fix(ios): add NSLock to nativeAcceptHandledCallIds and 10s REST timeout to handleNativeAccept (#7198) * feat(android): create VoipCallService with FOREGROUND_SERVICE_MICROPHONE (#7199) * fix(android): start VoipCallService on accept, stop on hangup/timeout, install end-call listener (#7200) * fix(voip): enable DM nav for users with SIP extension (#7203) * fix(android): handle null VoiceConnection in answerIncomingCall, notify JS (#7201) * fix(voip): resolve closure capture ordering in handleNativeAccept (#7209) * fix(android): integrate VoIP modules with SSL-pinned OkHttpClient (#7208) * fix(push): gate id and voipToken behind server version checks, fix VideoConf caller extra (#7210) * fix(voip): remove sensitive data from production logs (#7207) * fix(android): remove isRunning guard + add double-tap guard on Accept/Decline - VoipCallService: remove if (!isRunning) guard, call startForeground unconditionally (idempotent on Android, fixes Android 14+ foreground service requirement) - IncomingCallActivity: add AtomicBoolean guard on handleAccept/handleDecline to prevent double-tap from triggering multiple service starts --------- Co-authored-by: diegolmello <diegolmello@users.noreply.github.com> Co-authored-by: Pierre Lehnen <55164754+pierre-lehnen-rc@users.noreply.github.com>
Proposed changes
Create
VoipCallService— an Android foregroundServicewithforegroundServiceType="microphone"— so VoIP audio calls keep running when the app is backgrounded. Without a foreground service, Android terminates the process and drops the active WebRTC audio session, which is the same problem iOS solves via CallKit audio retention.What this adds
VoipCallService.kt— foreground service that starts/stops around the call lifecycle.startService(context, callId): starts in foreground with an ongoing notification.stopService(context): requests shutdown.ACTION_START/ACTION_STOPintent actions for explicit control.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONEon API 29+.AndroidManifest.xml— declares the service withforegroundServiceType="microphone",enabled="true",exported="false".Review fixes applied
Addresses CodeRabbit review findings #1 (production crash) and #2 (start-command semantics):
stopService()helper now callscontext.stopService(intent)instead ofcontext.startService(intent). On Android 8+ (API 26+), invokingstartServicefrom a background context throwsIllegalStateException/BackgroundServiceStartNotAllowedException— which is exactly when a hangup from a backgrounded or headless-notification flow happens.onStartCommandreturnsSTART_NOT_STICKYforACTION_START(wasSTART_STICKY). A redelivered null intent cannot recover the WebRTC peer connection, so sticky semantics would only log a warning and terminate anyway.stopSelf(startId)replacesstopSelf()in theACTION_STOPand unknown-action branches, so only the matching start token is released and no start counts are leaked.Issue(s)
N/A — internal VoIP work.
How to test or reproduce
ACTION_START), background the app, verify audio continues and the ongoing notification is visible.ACTION_STOP); verify the service stops withoutIllegalStateExceptionin logs.ACTION_STOPwhile the app is fully backgrounded; the service still tears down cleanly (this is the case the fix unblocks).Types of changes
Checklist
Further comments
Merge order
This is PR 3 of 6 in the VoIP Android integration series:
PR-2: fix(ios) DDP cleanup — independent(merged)PR-1: fix(ios) NSLock + timeout — independent(merged)Summary by CodeRabbit