call-screen
Version:
Capacitor plugin for full-screen call UI with Accept/Reject buttons, OneSignal integration, and cross-platform support
346 lines (259 loc) • 9 kB
Markdown
# Call Screen Plugin
A Capacitor plugin for full-screen call UI with Accept/Reject buttons, OneSignal integration, and cross-platform support.
## Features
- ✅ Full-screen call UI with accept/reject buttons
- ✅ Custom ringtone and vibration
- ✅ Works when app is closed (via OneSignal)
- ✅ Shows over lock screen
- ✅ Foreground service for reliable operation
- ✅ Cross-platform support (Android, iOS, Web)
- ✅ OneSignal integration for push notifications
- ✅ Room name support for call context
- ✅ Call action callbacks (accepted/rejected events)
## Installation
```bash
npm install call-screen
```
## Setup
### 1. Install OneSignal Plugin
```bash
npm install onesignal-cordova-plugin
```
### 2. Initialize OneSignal in your app
```typescript
import OneSignal from 'onesignal-cordova-plugin';
import { CallScreen } from 'call-screen';
// Initialize OneSignal
OneSignal.setAppId('YOUR_ONESIGNAL_APP_ID');
// Request notification permission
OneSignal.promptForPushNotificationsWithUserResponse(response => {
console.log('Prompt response:', response);
});
// Handle notifications when app is in foreground
OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
const notification = notificationReceivedEvent.getNotification();
const data = notification.additionalData;
// Check if this is an incoming call notification
if (data && data.notification_type === 'incoming_call') {
// Prevent OneSignal from showing default notification
notificationReceivedEvent.complete(null);
// Handle the call
handleIncomingCall(data);
} else {
// Let OneSignal show the default notification
notificationReceivedEvent.complete(notification);
}
});
// Handle notification clicks
OneSignal.setNotificationOpenedHandler(notification => {
const data = notification.notification.additionalData;
if (data && data.notification_type === 'incoming_call') {
handleIncomingCall(data);
}
});
// Handle incoming call
async function handleIncomingCall(data: any) {
try {
await CallScreen.handleIncomingCall({
username: data.username || 'Unknown Caller',
callId: data.call_id || Date.now().toString(),
roomName: data.room_name || ''
});
} catch (error) {
console.error('Error handling incoming call:', error);
}
}
```
## Usage
### Show Call Screen Manually
```typescript
import { CallScreen } from 'call-screen';
// Show call screen with room name
await CallScreen.showCallScreen({
username: 'John Doe',
callId: 'call_123',
roomName: 'Meeting Room A'
});
```
### Handle Incoming Call
```typescript
// This is called when a OneSignal notification is received
await CallScreen.handleIncomingCall({
username: 'Alice Smith',
callId: 'call_456',
roomName: 'Conference Room B'
});
```
### Listen for Call Actions
```typescript
// Listen for call acceptance/rejection
const callActionListener = await CallScreen.addListener('callAction', (event) => {
console.log('Call action:', event.action); // 'accepted' or 'rejected'
console.log('Caller:', event.username);
console.log('Call ID:', event.callId);
console.log('Room:', event.roomName); // optional
if (event.action === 'accepted') {
// Handle accepted call - connect to WebRTC, open call UI, etc.
connectToCall(event.username, event.callId, event.roomName);
} else {
// Handle rejected call - notify server, update UI, etc.
notifyCallRejected(event.username, event.callId, event.roomName);
}
});
// Clean up listener when done
await CallScreen.removeAllListeners('callAction');
```
### Stop Active Call
```typescript
await CallScreen.stopCall();
```
### Check Call Status
```typescript
const result = await CallScreen.isCallActive();
console.log('Call active:', result.isActive);
```
## OneSignal Integration
### Notification Payload Format
Send OneSignal notifications with this format:
```json
{
"app_id": "YOUR_ONESIGNAL_APP_ID",
"included_segments": ["All"],
"data": {
"notification_type": "incoming_call",
"username": "John Doe",
"call_id": "call_123",
"room_name": "Meeting Room A",
"is_call": true,
"call_type": "incoming"
},
"contents": {
"en": "Incoming call from John Doe"
},
"headings": {
"en": "Incoming Call"
}
}
```
### Testing Scenarios
1. **App in Foreground**: Call screen appears immediately
2. **App in Background**: Call screen appears over lock screen
3. **App Closed**: Call screen appears and ringtone plays
4. **Device Locked**: Call screen appears over lock screen
## Android Permissions
The plugin automatically requests these permissions:
- `FOREGROUND_SERVICE` - For reliable call service
- `WAKE_LOCK` - To wake device for calls
- `DISABLE_KEYGUARD` - To show over lock screen
- `VIBRATE` - For call vibration
- `MODIFY_AUDIO_SETTINGS` - For ringtone control
- `ACCESS_NOTIFICATION_POLICY` - To override Do Not Disturb
- `SYSTEM_ALERT_WINDOW` - To show over other apps
- `USE_FULL_SCREEN_INTENT` - For full-screen call UI
- `RECEIVE_BOOT_COMPLETED` - For app closed state
- `POST_NOTIFICATIONS` - For Android 13+ notifications
- `INTERNET` - For network operations
- `ACCESS_NETWORK_STATE` - For network status
## Troubleshooting
### Call screen doesn't appear when app is closed
1. Verify OneSignal integration is properly set up
2. Check notification payload format
3. Ensure `CallScreen.handleIncomingCall()` is called
4. Check device battery optimization settings
### No ringtone sound
1. Check device volume settings
2. Verify Do Not Disturb mode is not blocking audio
3. Grant notification policy access if prompted
4. Check that ringtone.mp3 exists in res/raw folder
### Call screen appears but buttons don't work
1. Check service binding in CallScreenActivity
2. Verify no crash logs in Android Studio
3. Ensure proper activity configuration
## Debugging
Monitor logs with:
```bash
adb logcat | grep -E "(CallNotification|CallScreen|OneSignal)"
```
Expected log output:
```
CallNotificationExtender: === handleNotification ===
CallNotificationService: === CallNotificationService onStartCommand called ===
CallNotificationService: Ringtone started successfully using custom ringtone from raw folder
CallScreenActivity: === CallScreenActivity onCreate ===
```
## API Reference
### CallScreen.showCallScreen(options)
Shows the call screen manually.
**Parameters:**
- `options.username` (string): Name of the caller
- `options.callId` (string, optional): Unique call identifier
- `options.roomName` (string, optional): Room name for call context
### CallScreen.handleIncomingCall(options)
Handles an incoming call from OneSignal notification.
**Parameters:**
- `options.username` (string): Name of the caller
- `options.callId` (string, optional): Unique call identifier
- `options.roomName` (string, optional): Room name for call context
### CallScreen.stopCall()
Stops the active call and closes the call screen.
### CallScreen.isCallActive()
Checks if there's an active call.
**Returns:** Promise<{ isActive: boolean }>
### CallScreen.addListener(eventName, listenerFunc)
Listen for call action events (accepted/rejected).
**Parameters:**
- `eventName` (string): Must be 'callAction'
- `listenerFunc` (function): Callback function that receives CallActionEvent
**Returns:** Promise<PluginListenerHandle>
### CallScreen.removeAllListeners(eventName)
Remove all listeners for a specific event.
**Parameters:**
- `eventName` (string): Event name to remove listeners for
### CallActionEvent Interface
```typescript
interface CallActionEvent {
action: 'accepted' | 'rejected';
username: string;
callId: string;
roomName?: string;
}
```
## Examples
See `onesignal-integration-example.ts` for a complete integration example.
### Complete Call Management Example
```typescript
import { CallScreen, CallActionEvent } from 'call-screen';
class CallManager {
private callActionListener: any;
constructor() {
this.setupCallListener();
}
private async setupCallListener() {
this.callActionListener = await CallScreen.addListener('callAction', (event: CallActionEvent) => {
if (event.action === 'accepted') {
this.handleCallAccepted(event);
} else {
this.handleCallRejected(event);
}
});
}
private handleCallAccepted(event: CallActionEvent) {
console.log(`Call accepted from ${event.username} in room: ${event.roomName || 'No room'}`);
// Connect to WebRTC, open call UI, etc.
}
private handleCallRejected(event: CallActionEvent) {
console.log(`Call rejected from ${event.username} in room: ${event.roomName || 'No room'}`);
// Notify server, update UI, etc.
}
async showIncomingCall(username: string, callId: string, roomName?: string) {
await CallScreen.handleIncomingCall({ username, callId, roomName });
}
async cleanup() {
if (this.callActionListener) {
await CallScreen.removeAllListeners('callAction');
}
}
}
```
## License
MIT