|
1 | 1 | // useAudioStreamer.ts |
2 | 2 | import { useState, useRef, useCallback, useEffect } from 'react'; |
3 | | -import { PermissionsAndroid, Platform } from 'react-native'; |
| 3 | +import { Alert, PermissionsAndroid, Platform } from 'react-native'; |
4 | 4 | import notifee, { AndroidImportance } from '@notifee/react-native'; |
5 | 5 | import NetInfo from '@react-native-community/netinfo'; |
6 | 6 |
|
@@ -53,10 +53,44 @@ async function ensureNotificationPermission() { |
53 | 53 | } |
54 | 54 | } |
55 | 55 |
|
| 56 | +// On Android 14+ (API 34+), FOREGROUND_SERVICE_MICROPHONE requires RECORD_AUDIO |
| 57 | +// FOREGROUND_SERVICE_MICROPHONE is automatically granted when RECORD_AUDIO is granted |
| 58 | +// We must ensure RECORD_AUDIO is granted BEFORE starting the foreground service |
| 59 | +async function ensureForegroundServiceMicPermission() { |
| 60 | + if (Platform.OS !== 'android' || Platform.Version < 34) { |
| 61 | + return true; |
| 62 | + } |
| 63 | + try { |
| 64 | + const audioGranted = await PermissionsAndroid.check( |
| 65 | + PermissionsAndroid.PERMISSIONS.RECORD_AUDIO |
| 66 | + ); |
| 67 | + |
| 68 | + if (!audioGranted) { |
| 69 | + console.log('[AudioStreamer] Requesting RECORD_AUDIO permission...'); |
| 70 | + const audioResult = await PermissionsAndroid.request( |
| 71 | + PermissionsAndroid.PERMISSIONS.RECORD_AUDIO |
| 72 | + ); |
| 73 | + if (audioResult !== PermissionsAndroid.RESULTS.GRANTED) { |
| 74 | + Alert.alert('RECORD_AUDIO permission is required for microphone foreground service. Please grant microphone permission in app settings.'); |
| 75 | + return false; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + console.log('[AudioStreamer] RECORD_AUDIO permission granted. FOREGROUND_SERVICE_MICROPHONE should be automatically available.'); |
| 80 | + return true; |
| 81 | + } catch (error) { |
| 82 | + console.error('[AudioStreamer] Error ensuring foreground service mic permission:', error); |
| 83 | + return false; |
| 84 | + } |
| 85 | +} |
| 86 | + |
56 | 87 | async function startForegroundServiceNotification(title: string, body: string) { |
57 | 88 | ensureFgsRegistered(); |
58 | 89 | await ensureNotificationPermission(); |
59 | | - |
| 90 | + const success = await ensureForegroundServiceMicPermission(); |
| 91 | + if (!success) { |
| 92 | + return; |
| 93 | + } |
60 | 94 | // Create channel if needed |
61 | 95 | await notifee.createChannel({ |
62 | 96 | id: FGS_CHANNEL_ID, |
|
0 commit comments