React Native CallKeep - GitHub

文章推薦指數: 80 %
投票人數:10人

On an incoming call, from react native, call RNCallKeep. ... ConnectionService that the device is ready to make outgoing calls via the native Phone app. Skiptocontent {{message}} react-native-webrtc / react-native-callkeep Public Notifications Fork 343 Star 663 iOSCallKitframeworkandAndroidConnectionServiceforReactNative License ISClicense 663 stars 343 forks Star Notifications Code Issues 176 Pullrequests 14 Actions Projects 0 Wiki Security Insights More Code Issues Pullrequests Actions Projects Wiki Security Insights react-native-webrtc/react-native-callkeep Thiscommitdoesnotbelongtoanybranchonthisrepository,andmaybelongtoaforkoutsideoftherepository. master Branches Tags Couldnotloadbranches Nothingtoshow {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default 8 branches 32 tags Code Clone HTTPS GitHubCLI UseGitorcheckoutwithSVNusingthewebURL. WorkfastwithourofficialCLI. Learnmore. OpenwithGitHubDesktop DownloadZIP LaunchingGitHubDesktop Ifnothinghappens,downloadGitHubDesktopandtryagain. LaunchingGitHubDesktop Ifnothinghappens,downloadGitHubDesktopandtryagain. LaunchingXcode Ifnothinghappens,downloadXcodeandtryagain. LaunchingVisualStudioCode Yourcodespacewillopenonceready. Therewasaproblempreparingyourcodespace,pleasetryagain. Latestcommit manuquentin Mergepullrequest#596fromohheyitskartik/localboardcastmanager-add-on … 4b1fa98 Jul19,2022 Mergepullrequest#596fromohheyitskartik/localboardcastmanager-add-on Android:addinglocalbroadcastmanagersupport(#594Fix) 4b1fa98 Gitstats 600 commits Files Permalink Failedtoloadlatestcommitinformation. Type Name Latestcommitmessage Committime .github Addgithubissuetemplate Sep9,2019 android addinglocalboardcastmanagersupport Jul9,2022 docs DocumenttheuseofforegroundServiceTypeinAndroid<11 May2,2021 example Mergepullrequest#564fromreact-native-webrtc/dependabot/npm_and_y… Apr15,2022 ios addselectedproperty May3,2022 .gitignore initialcommit Dec28,2016 .npmignore [Android]SplitsetupintoregisterPhoneAccountandregisterAndroidEv… Jul16,2020 AUTHORS Addedmyselftoauthors May3,2021 LICENSE Updatedocumentationandlicenceinfiles Aug14,2019 MIGRATION_v2_v3.md Preparev3release Aug20,2019 MIGRATION_v3_v4.md 4.0.0 Nov24,2020 README.md Mergepullrequest#549fromlinus-komnick/patch-1 Apr15,2022 RNCallKeep.podspec UseReactfordependencyinpodspec Dec2,2019 actions.js Addmissingcomma Jan18,2022 index.d.ts addselectedproperty May3,2022 index.js AddmissinghasVideoattributeinsomemethods Apr25,2022 package.json 4.3.3 Apr15,2022 Viewcode ReactNativeCallKeep Summary Demo Android iOS Installation Usage Setup Constants AndroidSelfManagedMode API getInitialEvents clearInitialEvents setAvailable setForegroundServiceSettings canMakeMultipleCalls setCurrentCallActive isCallActive getCalls displayIncomingCall answerIncomingCall startCall updateDisplay endCall endAllCalls rejectCall reportEndCallWithUUID setMutedCall setOnHold setConnectionState checkIfBusy checkSpeaker toggleAudioRouteSpeaker getAudioRoutes setAudioRoute supportConnectionService hasPhoneAccount(async) hasOutgoingCall(async) hasDefaultPhoneAccount checkPhoneAccountEnabled isConnectionServiceAvailable backToForeground removeEventListener registerPhoneAccount registerAndroidEvents Events didReceiveStartCallAction -answerCall -endCall -didActivateAudioSession -didDisplayIncomingCall -didPerformSetMutedCallAction -didToggleHoldCallAction -didChangeAudioRoute -didPerformDTMFAction -didLoadWithEvents -showIncomingCallUi -silenceIncomingCall -createIncomingConnectionFailed -checkReachability Example Receivingacallwhentheapplicationisnotreachable. PushKit Android11 Debug Android Troubleshooting Contributing License README.md ReactNativeCallKeep ReactNativeCallKeeputilisesabrandnewiOS10frameworkCallKitandAndroidConnectionServicetomakethelifeeasierforVoIPdevelopersusingReactNative. FormoreinformationaboutCallKitoniOS,pleaseseeOfficialCallKitFrameworkDocumentorIntroductiontoCallKitbyXamarin FormoreinformationaboutConnectionServiceonAndroid,pleaseseeAndroidDocumentationandBuildacallingapp ⚠️CallKitandConnectionServiceareonlyavailableonrealdevices,thislibrarywillnotworkonsimulators. Summary Demo Installation Usage Constants AndroidSelfManaged API Example PushKit Android11 Debug Troubleshooting Contributing License Demo Ademoofreact-native-callkeepisavailableinthewazo-react-native-demorepository. Android iOS Installation npminstall--savereact-native-callkeep #or yarnaddreact-native-callkeep iOS Android Usage Setup importRNCallKeepfrom'react-native-callkeep'; constoptions={ ios:{ appName:'Myappname', }, android:{ alertTitle:'Permissionsrequired', alertDescription:'Thisapplicationneedstoaccessyourphoneaccounts', cancelButton:'Cancel', okButton:'ok', imageName:'phone_account_icon', additionalPermissions:[PermissionsAndroid.PERMISSIONS.example], //RequiredtogetaudioinbackgroundwhenusingAndroid11 foregroundService:{ channelId:'com.company.my', channelName:'Foregroundserviceformyapp', notificationTitle:'Myappisrunningonbackground', notificationIcon:'Pathtotheresourceiconofthenotification', }, } }; RNCallKeep.setup(options).then(accepted=>{}); iOSonly. AlternativeoniOSyoucanperformsetupinAppDelegate.m.Doingthisallowscapturingeventspriortothereactnativeeventbridgebeingup.PleasebeawarethatcallingsetupinAppDelegate.mwillignoreanysubsequentcallstoRNCallKeep.setup();. @implementationAppDelegate -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions { self.bridge=[[RCTBridgealloc]initWithDelegate:selflaunchOptions:launchOptions]; [RNCallKeepsetup:@{ @"appName":@"AwesomeApp", @"maximumCallGroups":@3, @"maximumCallsPerCallGroup":@1, @"supportsVideo":@NO, }]; RCTRootView*rootView=[[RCTRootViewalloc]initWithBridge:self.bridge moduleName:@"App" initialProperties:nil]; //========OTHERCODEREDACTED========== returnYES; } options:Object ios:object appName:string(required) ItwillbedisplayedonsystemUIwhenincomingcallsreceived imageName:string(optional) Ifprovided,itwillbedisplayedonsystemUIduringthecall ringtoneSound:string(optional) Ifprovided,itwillbeplayedwhenincomingcallsreceived;thesystemwillusethedefaultringtoneifthisisnotprovided handleType:string|array(optional) Ifprovided,itwilltelliOSwhatkindofhandle(s)(number)yourappcanhandle. generic number(default) email includesCallsInRecents:boolean(optional) Ifprovided,callswillbeshownintherecentcallswhentrueandnotwhenfalse(ios11andabove)(Default:true) maximumCallGroups:string(optional) Ifprovided,themaximumnumberofcallgroupssupportedbythisapplication(Default:3) maximumCallsPerCallGroup:string(optional) Ifprovided,themaximumnumberofcallsinasinglegroup,usedforconferencing(Default:1,noconferencing) supportsVideo:boolean(optional) Ifprovided,whetherornottheapplicationsupportsvideocalling(Default:true) displayCallReachabilityTimeout:numberinms(optional) Ifprovided,startsatimeoutthatchecksiftheapplicationisreachableandendsthecallifnot(Default:null) You'llhavetocallsetReachable()assoonasyourJavascriptapplicationisstarted. android:object alertTitle:string(required) Whenaskingforphoneaccountpermission,weneedtoprovideratitlefortheAlerttoasktheuserforit alertDescription:string(required) Whenaskingforphoneaccountpermission,weneedtoprovideradescriptionfortheAlerttoasktheuserforit cancelButton:string(required) Cancelbuttonlabel okButton:string(required) Okbuttonlabel imageName:string(optional) TheimagetouseintheAndroidPhoneapplication'snativeUIforenabling/disablingcallingaccounts.Shouldbea48x48HDPI grayscalePNGimage.Mustbeinyourdrawableresourcesfortheparentapplication.Mustbelowercaseandunderscore(_)characters only,asJavadoesn'tlikecapitallettersonresources. additionalPermissions:[PermissionsAndroid](optional) Anyadditionalpermissionsyou'dlikeyourapptohaveatfirstlaunch.Canbeusedtosimplifypermissionflowsandavoid multiplepopupstotheuseratdifferenttimes. selfManaged:boolean(optional) Whensettotrue,callkeepwillconfigureitselftorunasaselfmanagedconnectionservice.Thisisanadvancedtopic,andit'sbesttorefertoGooglesDocumentationonthematter. displayCallReachabilityTimeout:numberinms(optional) Ifprovided,startsatimeoutthatchecksiftheapplicationisreachableandendsthecallifnot(Default:null) You'llhavetocallsetReachable()assoonasyourJavascriptapplicationisstarted. setupcallsinternallyregisterPhoneAccount,registerEventsandsetSettings. YoucanalternativelyjustcallsetSettings()withthesameoptionassetup()todefineonlyyoursettings. Constants Tomakepassingtherightintegerintomethodseasier,thereareconstantsthatareexportedfromthemodule. constCONSTANTS={ END_CALL_REASONS:{ FAILED:1, REMOTE_ENDED:2, UNANSWERED:3, ANSWERED_ELSEWHERE:4, DECLINED_ELSEWHERE:5, MISSED:6 } }; const{CONSTANTSasCK_CONSTANTS,RNCallKeep}from'react-native-callkeep'; console.log(CK_CONSTANTS.END_CALL_REASONS.FAILED)//outputs1 AndroidSelfManagedMode ThisfeatureisavailableonlyonAndroid. Androidsupportscallingappsrunninginwhat'scalled"SelfManaged".Thismeanstheappsareable(andrequired)toprovidetheirownUIformanagingcalls.ThisincludesbothincallUIelementsandincomingcallnotificationUI.Thismethodisallornothing.Youcan'tmixpartialelements,suchashavingacustomincallview,butusethedefaultincomingcallUI. Toimplementaselfmanagedcallingapp,thefollowingstepsarenecessary: SetselfManaged:trueinsetup. Onanincomingcall,fromreactnative,callRNCallKeep.displayIncomingCall CallKeepwillthenfiretheshowIncomingCallUievent. WhenshowIncomingCallUiisfired,youmustshowanincomingcallUI.Thiswouldbeahighprioritynotification(Android:Displaytime-sensitivenotifications). Iftheuseranswersthecall,youcalltheappropriateRNCallKeepactionssuchasanswerCallorendCall IncertaincasesAndroidwillnotallowyoutoshowanincomingcallnotification.Inthatcasethe'createIncomingConnectionFailed'eventisfiredandyoushouldrejecttheincomingSIPInvite. SelfManagedcallingappsareanadvancedtopic,andtherearemanystepsinvolvedinimplementingthem,butherearesomethingstokeepinmind: ReactNativeHeadlessTasksareagreatwaytoexecuteReactNativecode.RemembertostartuptheheadlesstaskasaForegroundService. AndroidwilldeprioritizeyourhighpriorityFCMnotificationsifyoufailtoshowanincomingcalluiwhenreceivingthem. YoucanavoidgettingfloodedwithstickyforegroundservicenotificationsbynotdefiningaForegroundServiceforCallKeep,andinsteadmanagingthisonyourown. ⚠️Tobeabletousetheselfmanagedmode,you'llhavetoaddtheREAD_CALL_LOGpermissioninyourandroid/src/main/AndroidManifest.xmlfile: API Method ReturnType iOS Android getInitialEvents() Promise ✅ ✅ clearInitialEvents() void> ✅ ✅ setAvailable() Promise ❌ ✅ setForegroundServiceSettings() Promise ❌ ✅ canMakeMultipleCalls() Promise ❌ ✅ setCurrentCallActive() Promise ❌ ✅ isCallActive() Promise ✅ ❌ getCalls() Promise ✅ ❌ displayIncomingCall() Promise ✅ ✅ answerIncomingCall() Promise ✅ ✅ startCall() Promise ✅ ✅ updateDisplay() Promise ✅ ✅ endCall() Promise ✅ ✅ endAllCalls() Promise ✅ ✅ rejectCall() Promise ✅ ✅ reportEndCallWithUUID() Promise ✅ ✅ setMutedCall() Promise ✅ ✅ setOnHold() Promise ✅ ✅ setConnectionState() Promise ❌ ✅ checkIfBusy() Promise ✅ ❌ checkSpeaker() Promise ✅ ❌ toggleAudioRouteSpeaker() Promise ❌ ✅ supportConnectionService() Promise ❌ ✅ hasPhoneAccount() Promise ❌ ✅ hasOutgoingCall() Promise ❌ ✅ hasDefaultPhoneAccount() Promise ❌ ✅ checkPhoneAccountEnabled() Promise ❌ ✅ isConnectionServiceAvailable() Promise ❌ ✅ backToForeground() Promise ❌ ✅ removeEventListener() void ✅ ✅ registerPhoneAccount() void ❌ ✅ registerAndroidEvents() void ❌ ✅ getInitialEvents IfthereweresomeactionsperformedbyuserbeforeJScontexthasbeencreated,thismethodwouldreturnearlyfiredevents.Thisisalternativeto"didLoadWithEvents"event. RNCallKeep.getInitialEvents(); clearInitialEvents ClearallpendingactionsreturnedbygetInitialEvents(). RNCallKeep.clearInitialEvents(); setAvailable ThisfeatureisavailableonlyonAndroid. TellConnectionServicethatthedeviceisreadytomakeoutgoingcallsviathenativePhoneapp. IfnottheuserwillbestuckinthebuildUIscreenwithoutanyactions. Eg:Callitwithfalsewhendisconnectedfromthesipclient,whenyourtokenexpires,whenyouruserlogout... Eg:Whenyourusedlogout(ortheconnectiontoyourserverisbroken,etc..),youhavetocallsetAvailable(false)soCallKeepwillrefusethecallandyouruserwillnotbestuckinthenativeUI. RNCallKeep.setAvailable(true); setForegroundServiceSettings ThisfeatureisavailableonlyonAndroid. ConfigurestheForegroundServiceusedforAndroid11togetmicrophoneaccessonbackground. SimilartosettheforegroundServicekeyinthesetup()method. RNCallKeep.setForegroundServiceSettings({ channelId:'com.company.my', channelName:'Foregroundserviceformyapp', notificationTitle:'Myappisrunningonbackground', notificationIcon:'Pathtotheresourceiconofthenotification', }); canMakeMultipleCalls ThisfeatureisavailableonlyonAndroid. Disablethe"Addcall"buttoninConnectionServiceUI. RNCallKeep.canMakeMultipleCalls(false);//Enabledbydefault active:boolean Tellwhethertheappisreadyornot setCurrentCallActive ThisfeatureisavailableonlyonAndroid. Markthecurrentcallasactive(eg:whenthecalleehasanswered). NecessarytosetthecorrectAndroidcapabilities(hold,mute)oncethecallissetasactive. Besuretosetthisonlyafteryourcallisreadyfortwowayaudio;usedbothincomingandoutgoingcalls. RNCallKeep.setCurrentCallActive(uuid); uuid:string TheuuidusedforstartCallordisplayIncomingCall isCallActive ThisfeatureisavailableonlyonIOS. ReturnstrueiftheUUIDpassedmatchesanexistingandansweredcall. ThiswillreturntrueONLYifthecallexistsandtheuserhasalreadyansweredthecall.Itwillreturnfalse ifthecalldoesnotexistorhasnotbeenanswered.ThisisexposedtobothReactNativeandNativesides. Thiswasexposedsoacallcanbecanceledifringingandtheuseransweredonadifferentdevice. RNCallKeep.isCallActive(uuid); uuid:string TheuuidusedforstartCallordisplayIncomingCall getCalls ThisfeatureisavailableonlyonIOS. ReturnsaPromise.Theresultwillbeanarraywithallcurrentcallsandtheirstates. RNCallKeep.getCalls(); response: [{ callUUID:"E26B14F7-2CDF-48D0-9925-532199AE7C48", hasConnected:true, hasEnded:false, onHold:false, outgoing:false, }] displayIncomingCall DisplaysystemUIforincomingcalls RNCallKeep.displayIncomingCall(uid,handle,localizedCallerName='',handleType='number',hasVideo=false,options=null); uuid:string Anuuidthatshouldbestoredandre-usedforstopCall. handle:string Phonenumberofthecaller localizedCallerName:string(optional) NameofthecallertobedisplayedonthenativeUI handleType:string(optional,iOSonly) generic number(default) email hasVideo:boolean(optional,iOSonly) false(default) true(youknow...whennotfalse) options:object(optional) ios:object supportsHolding:boolean(optional,defaulttrue) supportsDTMF:boolean(optional,defaulttrue) supportsGrouping:boolean(optional,defaulttrue) supportsUngrouping:boolean(optional,defaulttrue) android:object(currentlyno-op) answerIncomingCall UsethistotellthesdkauseransweredacallfromtheappUI. RNCallKeep.answerIncomingCall(uuid) uuid:string TheuuidusedforstartCallordisplayIncomingCall startCall Whenyoumakeanoutgoingcall,tellthedevicethatacallisoccurring.Theargumentlistisslightly differentoniOSandAndroid: iOS: RNCallKeep.startCall(uuid,handle,contactIdentifier,handleType,hasVideo); Android: RNCallKeep.startCall(uuid,handle,contactIdentifier); uuid:string Anuuidthatshouldbestoredandre-usedforstopCall. handle:string Phonenumberofthecallee contactIdentifier:string TheidentifierisdisplayedinthenativecallUI,andistypicallythenameofthecallrecipient. handleType:string(optional,iOSonly) generic number(default) email hasVideo:boolean(optional,iOSonly) false(default) true(youknow...whennotfalse) updateDisplay Usethistoupdatethedisplayafteranoutgoingcallhasstarted. RNCallKeep.updateDisplay(uuid,displayName,handle) uuid:string TheuuidusedforstartCallordisplayIncomingCall displayName:string(optional) NameofthecallertobedisplayedonthenativeUI handle:string Phonenumberofthecaller options:object(optional) ios:object hasVideo:boolean(optional) supportsHolding:boolean(optional) supportsDTMF:boolean(optional) supportsGrouping:boolean(optional) supportsUngrouping:boolean(optional) android:object(currentlyno-op) endCall Whenfinishanincoming/outgoingcall. (Whenuseractivelychoosestoendthecallfromyourapp'sUI.) RNCallKeep.endCall(uuid); uuid:string TheuuidusedforstartCallordisplayIncomingCall endAllCalls Endallongoingcalls. RNCallKeep.endAllCalls(); rejectCall Whenyourejectanincomingcall. RNCallKeep.rejectCall(uuid); uuid:string TheuuidusedforstartCallordisplayIncomingCall reportEndCallWithUUID Reportthatthecallendedwithouttheuserinitiating. (Notendedbyuser,isusuallyduetothefollowingreasons) RNCallKeep.reportEndCallWithUUID(uuid,reason); uuid:string TheuuidusedforstartCallordisplayIncomingCall reason:int Reasonfortheendcall Callfailed:1 Remoteuserendedcall:2 Remoteuserdidnotanswer:3 CallAnsweredelsewhere:4 Calldeclinedelsewhere:5(onAndroidthiswillmaptoRemoteuserendedcallifyouusetheconstants) Missed:6(oniOSthiswillmaptoremoteuserendedcall) Accessreasonsasconstants const{CONSTANTSasCK_CONSTANTS,RNCallKeep}from'react-native-callkeep'; RNCallKeep.reportEndCallWithUUID(uuid,CK_CONSTANTS.END_CALL_REASONS.FAILED); setMutedCall Switchthemicon/off. RNCallKeep.setMutedCall(uuid,true); uuid:string uuidofthecurrentcall. muted:boolean setOnHold Setacallon/offhold. RNCallKeep.setOnHold(uuid,true) uuid:string uuidofthecurrentcall. hold:boolean setConnectionState ThisfeatureisavailableonlyonAndroid. Changethestateofthecall RNCallKeep.setConnectionState(uuid,state) uuid:string uuidofthecurrentcall. state:SeeConnection.STATE_*documentation checkIfBusy ThisfeatureisavailableonlyonIOS. Checksifthereareanyactivecallsonthedeviceandreturnsapromisewithabooleanvalue(trueifthere'reactivecalls,falseotherwise). RNCallKeep.checkIfBusy(); checkSpeaker ThisfeatureisavailableonlyonIOS. Checksifthedevicespeakerisonandreturnsapromisewithabooleanvalue(trueifspeakerison,falseotherwise). RNCallKeep.checkSpeaker(); toggleAudioRouteSpeaker ThisfeatureisavailableonlyonAndroid. UpdatetheaudiorouteofAudioServiceonAndroidwitharouteSpeakerbooleanvalue(trueifspeakerneedon,falseotherwise). WhenPhonecallisactive,Androidcontroltheaudioviaconnectionservice.sothisfunctionhelptotoggletheaudiotoSpeakerorwired/ear-pieceorvice-versa RNCallKeep.toggleAudioRouteSpeaker(uuid,true); uuid:string uuidofthecurrentcall. routeSpeaker:boolean getAudioRoutes Getthelistofavailableaudioroutes.i.e.bluetooth,wired/ear-piece,speakerandphone. awaitRNCallKeep.getAudioRoutes():AudioRoute; typeAudioRoute={ name:string, type:string } setAudioRoute SetaudiorouteusingaroutefromgetAudioRoutes. awaitRNCallKeep.setAudioRoute(uuid,routeName); uuid:string uuidofthecurrentcall. routeName:String AudioRoute.name. supportConnectionService ThisfeatureisavailableonlyonAndroid. TellsifConnectionServiceisavailableonthedevice(returnsaboolean). RNCallKeep.supportConnectionService(); hasPhoneAccount(async) ThisfeatureisavailableonlyonAndroid. Checksiftheuserhasenabledthephoneaccountforyourapplication. AphoneaccountmustbeenabletobeabletodisplayUIscreenonincomingcallandmakeoutgoingcallsfromnativeContactapplication. Returnsapromiseofaboolean. awaitRNCallKeep.hasPhoneAccount(); hasOutgoingCall(async) ThisfeatureisavailableonlyonAndroid,usefulwhenwakinguptheapplicationforanoutgoingcall. WhenwakinguptheAndroidapplicationinbackgroundmode(eg:whentheapplicationiskilledandtheusermakeacallfromthenativePhoneapplication). Theusercanhangupthecallbeforeyourapplicationhasbeenstartedinbackgroundmode,andyoucanlosttheRNCallKeepPerformEndCallActionevent. Tobesurethattheoutgoingcallisstillhere,youcancallhasOutgoingCallwhenyouappwakenup. consthasOutgoingCall=awaitRNCallKeep.hasOutgoingCall(); hasDefaultPhoneAccount ThisfeatureisavailableonlyonAndroid. Checksiftheuserhassetadefaultphoneaccount. Iftheuserhasnotsetadefaulttheywillbepromptedtodosowithanalert. ThisisaworkaroundforanissueaffectingsomeSamsungdevices. constoptions={ alertTitle:'Defaultnotset', alertDescription:'Pleasesetthedefaultphoneaccount' }; RNCallKeep.hasDefaultPhoneAccount(options); checkPhoneAccountEnabled ThisfeatureisavailableonlyonAndroid. Checksiftheuserhassetadefaultphoneaccountandit'senabled. It'susefulforcustompermissionprompts.ItshouldbeusedinpairwithregisterPhoneAccount SimilartohasDefaultPhoneAccountbutwithouttrigeringapromptiftheuserdoesn'thaveaphoneaccount. RNCallKeep.checkPhoneAccountEnabled(); isConnectionServiceAvailable ThisfeatureisavailableonlyonAndroid. CheckifthedevicesupportConnectionService. RNCallKeep.checkPhoneAccountEnabled(); backToForeground ThisfeatureisavailableonlyonAndroid. Usethistodisplaytheapplicationinforegroundiftheapplicationwasinbackgroundstate. Thismethodwillopentheapplicationifitwasclosed. RNCallKeep.backToForeground(); removeEventListener Allowstoremovethelisteneronanevent. RNCallKeep.removeEventListener('checkReachability'); registerPhoneAccount RegistersAndroidphoneaccountmanually,usefulforcustompermissionpromptswhenyoudon'twanttocallsetup(). Thismethodiscalledbysetup,ifyoualreadyusesetupyoudon'tneedit. ThisfeatureisavailableonlyonAndroid. OniOSyoustillhavetocallsetup(). RNCallKeep.registerPhoneAccount(options); registerAndroidEvents RegistersAndroidUIevents,usefulwhenyoudon'twanttocallsetup(). Thismethodiscalledbysetup,ifyoualreadyusesetupyoudon'tneedit. ThisfeatureisavailableonlyonAndroid. OniOSyoustillhavetocallsetup(). RNCallKeep.registerAndroidEvents(); Events Event iOS Android didReceiveStartCallAction ✅ ✅ answerCall ✅ ✅ endCall ✅ ✅ didActivateAudioSession ✅ ✅ didDisplayIncomingCall ✅ ✅ didPerformSetMutedCallAction ✅ ✅ didToggleHoldCallAction ✅ ✅ didPerformDTMFAction ✅ ✅ didLoadWithEvents ✅ ✅ showIncomingCallUi ❌ ✅ silenceIncomingCall ❌ ✅ checkReachability ❌ ✅ didChangeAudioRoute ✅ ✅ didReceiveStartCallAction Devicesendsthiseventonceitdecidestheappisallowedtostartacall,eitherfromthebuilt-inphonescreens(iOS/Recents,Android/Contact), orbytheappcallingRNCallKeep.startCall. Trytostartyourappcallactionfromhere(e.g.getcredentialsoftheuserbydata.handleand/orsendINVITEtoyourSIPserver) Note:oniOScallUUIDisnotdefinedasthecallisnotyetmanagedbyCallKit.YouhavetogenerateyourownandcallstartCall. RNCallKeep.addEventListener('didReceiveStartCallAction',({handle,callUUID,name})=>{ }); handle(string) Phonenumberofthecallee callUUID(string) TheUUIDofthecallthatistobeanswered name(string) Nameofthecallee -answerCall Useranswertheincomingcall RNCallKeep.addEventListener('answerCall',({callUUID})=>{ //Doyournormal`Answering`actionshere. }); callUUID(string) TheUUIDofthecallthatistobeanswered. -endCall Userfinishthecall. RNCallKeep.addEventListener('endCall',({callUUID})=>{ //Doyournormal`HangUp`actionshere }); callUUID(string) TheUUIDofthecallthatistobeended. -didActivateAudioSession TheAudioSessionhasbeenactivatedbyRNCallKeep. RNCallKeep.addEventListener('didActivateAudioSession',()=>{ //youmightwanttodofollowingthingswhenreceivingthisevent: //-Startplayingringbackifitisanoutgoingcall }); -didDisplayIncomingCall CallbackforRNCallKeep.displayIncomingCall RNCallKeep.addEventListener('didDisplayIncomingCall',({error,callUUID,handle,localizedCallerName,hasVideo,fromPushKit,payload})=>{ //youmightwanttodofollowingthingswhenreceivingthisevent: //-Startplayingringbackifitisanoutgoingcall }); error(string) iOSonly. errorCode(string) iOSonly.Possiblevalues:"Unentitled","CallUUIDAlreadyExists","FilteredByDoNotDisturb","FilteredByBlockList","Unknown".Seehttps://developer.apple.com/documentation/callkit/cxerrorcodeincomingcallerrorformoreinformation. callUUID(string) TheUUIDofthecall. handle(string) Phonenumberofthecaller localizedCallerName(string) NameofthecallertobedisplayedonthenativeUI hasVideo(string) 1(videoenabled) 0(videonotenabled) fromPushKit(string) 1(calltriggeredfromPushKit) 0(callnottriggeredfromPushKit) payload(object) VOIPpushpayload. -didPerformSetMutedCallAction Acallwasmutedbythesystemortheuser: RNCallKeep.addEventListener('didPerformSetMutedCallAction',({muted,callUUID})=>{ }); muted(boolean) callUUID(string) TheUUIDofthecall. -didToggleHoldCallAction Acallwasheldorunheldbythecurrentuser RNCallKeep.addEventListener('didToggleHoldCallAction',({hold,callUUID})=>{ }); -didChangeAudioRoute Triggeredwhentheaudioroutehasbeenchanged. ⚠️WillsendSpeakeroniOSbutSPEAKERonAndroid. RNCallKeep.addEventListener('didChangeAudioRoute',({output})=>{ }); hold(boolean) callUUID(string) TheUUIDofthecall. -didPerformDTMFAction Usedtypeanumberonhisdialer RNCallKeep.addEventListener('didPerformDTMFAction',({digits,callUUID})=>{ }); digits(string) Thedigitsthatemitthedtmftone callUUID(string) TheUUIDofthecall. -didLoadWithEvents iOSonly. CalledassoonasJScontextinitializesifthereweresomeactionsperformedbyuserbeforeJScontexthasbeencreated. SinceiOS13,youmustdisplayincomingcallonreceivingPushKitpushnotification.Butifappwaskilled,ittakessometimetocreateJScontext.Ifuseranswersthecall(orendsit)beforeJScontexthasbeeninitialized,useractionswillbepassedaseventsarrayofthisevent.SimilarsituationcanhappenifuserwouldliketostartacallfromRecentsorsimilariOSapp,assumingthatyourappwasinkilledstate. Inorderforthiseventtoreliablyfire,it'snecessarytoperformsetupinAppDelegate.m NOTE:Youstillneedtosubscribe/handletheresteventsasusuall.Thisisjustahelperwhcihcacheandpropagateearlyfiredeventsifandonlyiffor"thenativeeventswhichDIDfireBEFOREjsbridgeisinitialed",itdoesNOTmeanthiswillhaveeventseachtimewhentheappreopened. //register`didLoadWithEvents`somewhereearlyinyourappwhenitisreadytohandlecallkeepevents. RNCallKeep.addEventListener('didLoadWithEvents',(events)=>{ //`events`ispassedasanArraychronologically,handleorignoreeventsbasedontheapp'slogic //seeexampleusageinhttps://github.com/react-native-webrtc/react-native-callkeep/pull/169orhttps://github.com/react-native-webrtc/react-native-callkeep/pull/205 }); eventsArray name:string Nativeeventnamelike:RNCallKeepPerformAnswerCallAction data:object Objectwithdatapassedtogetherwithspecificeventsoitcanbehandledinthesamewaylikeoriginalevent,forexample({callUUID})foranswerCalleventifnameisRNCallKeepPerformAnswerCallAction -showIncomingCallUi Androidonly.SelfManagedonly. OnlywhenCallKeepissetuptobeinselfmanagedmode.SignalsthattheappmustshowanincomingcallUI.TheimplementormusteithercalldisplayIncomingCallfromreactnativeornativeandroidcodetomakethiseventfire. RNCallKeep.addEventListener('showIncomingCallUi',({handle,callUUID,name})=>{ }); ThefollowingvalueswillmatchthoseinitiallypassedtodisplayIncomingCall handle(string) Phonenumberoftheincomingcaller. callUUID(string) TheUUIDofthecall. name(string) CallerName. -silenceIncomingCall Androidonly.SelfManagedonly. CorrespondstothenativeonSilenceevent.Theimplementorshouldsilencethecorrespondingincomingcallsnotificationsoundwhenandifthiseventisfired. RNCallKeep.addEventListener('silenceIncomingCall',({handle,callUUID,name})=>{ }); ThefollowingvalueswillmatchthoseinitiallypassedtosilenceIncomingCall handle(string) Phonenumberoftheincomingcaller. callUUID(string) TheUUIDofthecall. name(string) CallerName. -createIncomingConnectionFailed Androidonly.SelfManagedonly. CorrespondstothenativeonCreateIncomingConnectionFailedcallback.TheimplementorshouldrejecttheincomingSIPINVITEwithanappropriatestatuscode,suchas483UserBusy.Androidunfortunatelydoesnotprovidetheexactreasonforrefusingtoletyouacceptanincomingcall,buttheydolistasetofreasonshere RNCallKeep.addEventListener('createIncomingConnectionFailed',({handle,callUUID,name})=>{ }); ThefollowingvalueswillmatchthoseinitiallypassedtosilenceIncomingCall handle(string) Phonenumberoftheincomingcaller. callUUID(string) TheUUIDofthecall. name(string) CallerName. -checkReachability Androidonly. OnAndroidwhentheapplicationisinbackground,afteracertaindelaytheOSwillcloseeveryconnectionwithinformingaboutit. Sowehavetocheckiftheapplicationisreachablebeforemakingacallfromthenativephoneapplication. RNCallKeep.addEventListener('checkReachability',()=>{ RNCallKeep.setReachable(); }); Example Afullexampleisavailableintheexamplefolder. importReactfrom'react'; importRNCallKeepfrom'react-native-callkeep'; importuuidfrom'uuid'; classRNCallKeepExampleextendsReact.Component{ constructor(props){ super(props); this.currentCallId=null; //AddRNCallKeepEvents RNCallKeep.addEventListener('didReceiveStartCallAction',this.didReceiveStartCallAction); RNCallKeep.addEventListener('answerCall',this.onAnswerCallAction); RNCallKeep.addEventListener('endCall',this.onEndCallAction); RNCallKeep.addEventListener('didDisplayIncomingCall',this.onIncomingCallDisplayed); RNCallKeep.addEventListener('didPerformSetMutedCallAction',this.onToggleMute); RNCallKeep.addEventListener('didToggleHoldCallAction',this.onToggleHold); RNCallKeep.addEventListener('didPerformDTMFAction',this.onDTMFAction); RNCallKeep.addEventListener('didActivateAudioSession',this.audioSessionActivated); } //InitialiseRNCallKeep setup=()=>{ constoptions={ ios:{ appName:'ReactNativeWazoDemo', imageName:'sim_icon', supportsVideo:false, maximumCallGroups:'1', maximumCallsPerCallGroup:'1' }, android:{ alertTitle:'PermissionsRequired', alertDescription: 'Thisapplicationneedstoaccessyourphonecallingaccountstomakecalls', cancelButton:'Cancel', okButton:'ok', imageName:'sim_icon', additionalPermissions:[PermissionsAndroid.PERMISSIONS.READ_CONTACTS] } }; try{ RNCallKeep.setup(options); RNCallKeep.setAvailable(true);//OnlyusedforAndroid,seedocabove. }catch(err){ console.error('initializeCallKeeperror:',err.message); } } //UsestartCalltoaskthesystemtostartacall-Initiateanoutgoingcallfromthispoint startCall=({handle,localizedCallerName})=>{ //Yournormalstartcallaction RNCallKeep.startCall(this.getCurrentCallId(),handle,localizedCallerName); }; reportEndCallWithUUID=(callUUID,reason)=>{ RNCallKeep.reportEndCallWithUUID(callUUID,reason); } //EventListenerCallbacks didReceiveStartCallAction=(data)=>{ let{handle,callUUID,name}=data; //Getthiseventafterthesystemdecidesyoucanstartacall //Youcannowstartacallfromwithinyourapp }; onAnswerCallAction=(data)=>{ let{callUUID}=data; //Calledwhentheuseranswersanincomingcall }; onEndCallAction=(data)=>{ let{callUUID}=data; RNCallKeep.endCall(this.getCurrentCallId()); this.currentCallId=null; }; //CurrentlyiOSonly onIncomingCallDisplayed=(data)=>{ let{error}=data; //YouwillgetthiseventafterRNCallKeepfinishesshowingincomingcallUI //Youcancheckiftherewasanerrorwhiledisplaying }; onToggleMute=(data)=>{ let{muted,callUUID}=data; //Calledwhenthesystemorusermutesacall }; onToggleHold=(data)=>{ let{hold,callUUID}=data; //Calledwhenthesystemoruserholdsacall }; onDTMFAction=(data)=>{ let{digits,callUUID}=data; //CalledwhenthesystemoruserperformsaDTMFaction }; audioSessionActivated=(data)=>{ //youmightwanttodofollowingthingswhenreceivingthisevent: //-Startplayingringbackifitisanoutgoingcall }; getCurrentCallId=()=>{ if(!this.currentCallId){ this.currentCallId=uuid.v4(); } returnthis.currentCallId; }; render(){ } } Receivingacallwhentheapplicationisnotreachable. Insomecaseyourapplicationcanbeunreachable: whentheuserkilltheapplication whenit'sinbackgroundsincealongtime(eg:after~5mntheoswillkillallconnections). Tobeabletowakeupyourapplicationtodisplaytheincomingcall,youcanusehttps://github.com/react-native-webrtc/react-native-voip-push-notificationoniOSorBackgroundMessagingfromreact-native-firebase-(Optional)(Android-only)-Listen-for-FCM-messages-in-the-background). Youhavetosendapushtoyourapplication,likewithFirebaseforAndroidandwithalibrarysupportingPushKitpushesforiOS. PushKit SinceiOS13,you'llhavetoreporttheincomingcallsthatwakesupyourapplicationwithaVoIPpush.AddthisinyourAppDelegate.mifyou'reusingVoIPpushestowakeupyourapplication: -(void)pushRegistry:(PKPushRegistry*)registrydidReceiveIncomingPushWithPayload:(PKPushPayload*)payloadforType:(PKPushType)typewithCompletionHandler:(void(^)(void))completion{ //Processthereceivedpush [RNVoipPushNotificationManagerdidReceiveIncomingPushWithPayload:payloadforType:(NSString*)type]; //RetrieveinformationlikehandleandcallerNamehere //NSString*uuid=/*fetchforpayloador...*/[[[NSUUIDUUID]UUIDString]lowercaseString]; //NSString*callerName=@"callernamehere"; //NSString*handle=@"callernumberhere"; //NSDictionary*extra=[payload.dictionaryPayloadvalueForKeyPath:@"custom.path.to.data"];/*usethistopassanyspecialdata(ie.fromyournotification)downtoRN.Canalsobe`nil`*/ [RNCallKeepreportNewIncomingCall:uuid handle:handle handleType:@"generic" hasVideo:NO localizedCallerName:callerName supportsHolding:YES supportsDTMF:YES supportsGrouping:YES supportsUngrouping:YES fromPushKit:YES payload:extra withCompletionHandler:completion]; } Android11 SinceAndroid11,yourapplicationrequirestostartaforegroundServiceinordertoaccessthemicrophoneinbackground. You'llneedtoupgradeyourcompileSdkVersionto30tobeabletousethisfeature. YouhavetosettheforegroundServicekeyinthesetup()methodandaddaforegroundServiceTypeintheAndroidManifestfile. Debug Android adblogcat*:SRNCallKeep:V Troubleshooting Ensurethatyouconstructavaliduuidbyimportingtheuuidlibraryandrunninguuid.v4()asshownintheexamples.Ifyoudon'tdothisanduseacustomstring,theincomingcallscreenwillneverbeshownoniOS. Contributing Anypullrequest,issuereportandsuggestionarehighlywelcome! License Thisworkisdual-licensedunderISCandMIT. Previousworkdoneby@ianlinoniOSisonISCLicence. WechooseMITfortherestoftheproject. SPDX-License-Identifier:ISCORMIT About iOSCallKitframeworkandAndroidConnectionServiceforReactNative Topics android ios react-native webrtc voip callkit connectionservice connection-service call-kit Resources Readme License ISClicense Stars 663 stars Watchers 25 watching Forks 343 forks Releases 27 4.3.3 Latest Apr15,2022 +26releases Packages0 Nopackagespublished Usedby252 +244 Contributors56 +45contributors Languages Java 57.8% Objective-C 27.3% JavaScript 12.5% Starlark 1.3% Ruby 1.1% Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?