Android Question Incoming Phone Calls with GPS Service

bocker77

Active Member
Licensed User
Longtime User
Just wanting to run this solution past some of you fine people to see if I am doing this right.

While driving and using my app to detect historical markers, my phone locked up hard. It took a while to get it to shutdown and reboot. The last event that I could tell was that I received an incoming phone call. I can't be sure that this is what caused the issue though. I will need to test this out which will not be easy. Anyway I decided to see if there was something that I could do to hopefully eleviate this.

My app utilizes a service that continuously monitors GPS coordinate changes. I got a good hit in this forum on how to detect incoming phone calls. If this occurs I can stop GPS. I am wondering if the below code is sufficient. Also not sure when discovering an incoming phone call it would be too late to stop GPS so not get the hang.

Here is the GPS service routine.
B4X:
#Region  Service Attributes 
    #StartAtBoot: False    
#End Region

'B4XPages.IsInitialized

Sub Process_Globals    
    Private nid As Int = 1
    Public GPS1 As GPS
    Private Tracking As Boolean
    Private lock As PhoneWakeState
    Dim PES As PhoneEvents
    Dim PID As PhoneId
    Dim bNoNetwork As Boolean
    Private tmr As Timer
    Dim strState As String
    Dim iCount As Int
End Sub
' Get the GPS ball started
Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
    GPS1.Initialize("GPS")
    If GPS1.GPSEnabled = False Then
        ToastMessageShow("Please enable the GPS device.", True)
        StartActivity(GPS1.LocationSettingsIntent) 'Will open the relevant settings screen.
    End If
    ' These keep battery usage down
    lock.PartialLock
    lock.KeepAlive(False)
    ' Determine when there is a network change
    PES.InitializeWithPhoneState("PES", PID)
End Sub
' Continuously run the service
Sub Service_Start (StartingIntent As Intent)
    Service.StartForeground(nid, CreateNotification)
    Track
End Sub
' Startup GPS
Public Sub Track
    If Tracking Then Return
    GPS1.Start(0,0) 'Listen to GPS with no filters
    Tracking = True
End Sub
Sub GPS_UserEnabled (Enabled As Boolean)
    If Enabled Then
        B4XPages.MainPage.bGPS = True
    End If
End Sub
' Send GPS coordinates to the main module - the engine that makes everything work
Sub GPS_LocationChanged (Location1 As Location)
    ' Stop sending locations if in the process of loading the List, comparing for markers or no network connection
    If B4XPages.MainPage.bLoadingCLV Or _
       B4XPages.MainPage.bComparing Or _
       bNoNetwork Then Return
    B4XPages.MainPage.LocationChanged(Location1)
End Sub
' Send a cautionary notification about app's battery usage
Sub CreateNotification As Notification
    Dim n As NB6    
    Dim cs As CSBuilder
    
    Dim bmpSign As Bitmap = LoadBitmapResize(File.DirAssets, "sign.png", 24dip, 24dip, False)
    Dim title As Object = cs.Initialize.Color(Colors.Red).Append("Caution:").PopAll
    Dim Content As Object
    Content = cs.Initialize.Append("This app may drain your battery!").PopAll
    Dim largeIcon As Bitmap = LoadBitmapResize(File.DirAssets, "Small Cartoon.png", 256dip, 256dip, True)
    n.Initialize("default", Application.LabelName, "DEFAULT").AutoCancel(True).SmallIcon(bmpSign)
    n.LargeIcon(largeIcon)
    Return n.Build(title, Content, "tag", Me)
End Sub
'ConnectivityChanged - There was a change in the state of the WIFI network or the MOBILE network (other network).
'NetworkType - WIFI Or MOBILE.
'State - One of the following values: CONNECTING, CONNECTED, SUSPENDED, DISCONNECTING, DISCONNECTED, UNKNOWN.
Sub PES_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
'    ToastMessageShow("NetworkType: " & NetworkType & CRLF & "State: " & State, True)
    If State = "CONNECTING" Or State = "DISCONNECTING" Then Return
    
    strState = State
    If State = "DISCONNECTED" Or _
       State = "SUSPENDED" Or _
       State = "UNKNOWN" Then
        iCount = 0
        tmr.Initialize("timer", 2000)
        tmr.Enabled = True
        Return
    Else If State = "CONNECTED" Then
        If bNoNetwork Then
            B4XPages.MainPage.ConnectionLost("Reconnected")
            bNoNetwork = False
'        Else If NetworkType = "MOBILE" Then
'            CallSub(B4XPages.Main.GoingMobi)
        Else
            Return
        End If
    End If
End Sub
' Handle phone calls
Sub PES_PhoneStateChanged (State As String, IncomingNumber As String, Intent As Intent)
    Select State
        ' Handle the incoming phone call
        Case "RINGING"
            GPS1.Stop
        ' Handle the call ending
        Case "IDLE"
            GPS1.Start(0,0)
    End Select
End Sub
' Determine if the internet connection is really down or just in the process of switching between wifi and mobile
Sub timer_Tick
    If strState = "CONNECTED" Then 
        tmr.Enabled = False
    End If
    iCount = iCount + 1
    If iCount > 5 Then
'        Log("No Network")
        tmr.Enabled = False        
        bNoNetwork = True
        B4XPages.MainPage.ConnectionLost("Disconnected")
    End If
End Sub
' End the service module
Sub Service_Destroy
    If Tracking Then
        GPS1.Stop
    End If
    Tracking = False
    lock.ReleaseKeepAlive
    lock.ReleasePartialLock
End Sub

I believe from reading that I do not need to add this line to the Manifest because of using "PES.InitializeWithPhoneState("PES", PID)".
B4X:
'******** Detect Phone Calls ***************
AddPermission(android.permission.READ_PHONE_STATE)

BTW I am liking the B4X documentation in Google AI!
 

JohnC

Expert
Licensed User
Longtime User
Is there a reason why you want your app to stop GPS when you get a phone call?
 
Last edited:
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
The reason is because I was driving past a known historical marker and it did not detect it. When pulling off the side of the road I was then able to view my phone. It was there that I saw that I had an incoming phone call with no ring and the phone was locked up. After several minutes of messing with the on/off button I was able to get it to reboot. I am thinking that during that time the OS started killing processes.

I am able to get my daughter to ride with me and see if I can reproduce the error. I need to role out if the error is in the service module or in the main program. This will be having her call my phone as the service is busy doing its thing while driving, massive changes with the GPS coordinates. And also calling my phone while the program reads the verbiage (TTS) on a detected marker. Hopefully with one of these two tests then I can reproduce the error.

As a side note I have successfully driven hundreds of miles using the program with no issues. And in those times I do not believe I ever got an incoming phone call.

I am going to look at peacemaker's link and see if I can put the phone in incoming calls going to voicemail instead of shutting GPS off and on around a phone call. This is if I can figure out where the error is occuring.
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
Just tested with numerous conditions and no issues. I am not ruling out that it was my program that caused the lockup though. So now I have to learn about crash files and see if I have one on my phone. I do have my phone in Development Mode so hopefully I have one.
 
Upvote 0
Top