Android Code Snippet PhoneStateChanged sample: all possible calling states

I have reworked my old code sample basing on StackOverflow example code:

B4X:
'Service module
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim PE As PhoneEvents
    Dim PhId As PhoneId
 
    Dim callStartTime, callEndTime As Long
    Dim isIncoming As Boolean
    Dim lastState As String = "IDLE"
    Dim savedNumber As String
End Sub

Sub Service_Create
lastState = "IDLE"
PE.InitializeWithPhoneState("PE",PhId)
End Sub

Sub PE_PhoneStateChanged (State As String, IncomingNumber As String, Intent As Intent)
    'Incoming call-  goes from IDLE To RINGING when it rings, To OFFHOOK when it's answered, to IDLE when its hung up
    'Outgoing call-  goes from IDLE To OFFHOOK when it dials out, To IDLE when hung up
 
    If State = lastState Then
        Return
    End If
    Select State
        Case "RINGING"
            'calling in progress
            isIncoming = True
            callStartTime = DateTime.Now
            savedNumber = IncomingNumber
       
            Exit
        Case "OFFHOOK"
            'Transition of ringing->offhook are pickups of incoming calls.  Nothing donw on them
            If lastState <> "RINGING" Then
                'outgoing call start
                isIncoming = False
                callStartTime = DateTime.Now
           
            End If
            Exit
        Case "IDLE"
            'Went to idle-  this is the end of a call.  What type depends on previous state(s)
            If lastState = "RINGING" Then
                'missed call
                callEndTime = 0
            else if isIncoming Then
                'incoming call is finished
                callEndTime = DateTime.Now
            Else
                'outgoing call is finished
                callEndTime = DateTime.Now
            End If
       
            Exit
    End Select
    lastState = State
 
    'Log("PhoneStateChanged, State = " & State & ", IncomingNumber = " & IncomingNumber & "; PhoneFlag = " & PhoneFlag)
End Sub

Depends on: Phone lib
DO not forget at an activity to request PERMISSION_READ_PHONE_STATE.
 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…