Android Question Phone ConnectivityChanged Event Not Getting Triggered

bocker77

Active Member
Licensed User
Longtime User
I have the following service where I want to detect when the phone goes from WiFi to Mobile and vice versa. Sub PE_ConnectivityChanged gets called only at startup of the service. When testing I turn off WiFi but it never goes to this sub. Do I need to do something else either in my code or in my testing to get this to trigger?

In B4a Log:
ConnectivityChanged: WIFI, state = CONNECTED

B4X:
#Region  Service Attributes 
    #StartAtBoot: False
    
#End Region

Sub Process_Globals    
    Private nid As Int = 1
    Public GPS1 As GPS
    Private Tracking As Boolean
    Private lock As PhoneWakeState
    Dim PE As PhoneEvents
    Dim PhoneId As PhoneId
End Sub

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
    ' Determine when there is a network change
    PE.InitializeWithPhoneState("PE", PhoneId)
    ' These keeps battery usage down
    lock.PartialLock
    lock.KeepAlive(False)
End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StartForeground(nid, CreateNotification)
    Track
End Sub

Public Sub Track
    If Tracking Then Return
    GPS1.Start(0,0) 'Listen to GPS with no filters
    Tracking = True
End Sub

Sub GPS_LocationChanged (Location1 As Location)
    ' Determine if in the process of loading the List or comparing GPS coordinates
    If Main.bLoadingCLV Or Main.bComparing Then Return
    CallSub2(Main, "LocationChanged", Location1)
End Sub

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

Sub PE_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
    Log("ConnectivityChanged: " & NetworkType & ", state = " & State)

End Sub

Sub Service_Destroy
    If Tracking Then
        GPS1.Stop
    End If
    Tracking = False
    lock.ReleaseKeepAlive
    lock.ReleasePartialLock
End Sub

Thanks for any help with this question,
Greg
 

Peter Simpson

Expert
Licensed User
Longtime User
@bocker77 your code works perfectly fine here, I just copied and pasted it directly into a B4XPage.


In reality all you need is the following code
B4X:
Sub Class_Globals
    Private Root As B4XView
    Private XUI As XUI

    Private PE As PhoneEvents
End Sub

Public Sub Initialize
    PE.Initialize("PE")
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub PE_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
    Log("ConnectivityChanged: " & NetworkType & ", state = " & State)
End Sub

Enjoy...
 
Last edited:
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
Thanks Peter for the response. In the documentation for PhoneEvents Erel says to put this code in a Service Module. I guess it doesn't need to be though.

Under PhoneEvents
...
Usually you will want to add this object to a Service module instead of an Activity module in order not to miss events that happen while
your activity is paused.
...
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
I moved it to the Activity and now the Service dies. So much for that.

Logger connected to: LGE LG-M150
--------- beginning of crash
--------- beginning of system
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
ConnectivityChanged: WIFI, state = CONNECTED
Bundle[{networkInfo=[type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "XXXXXXXX", roaming: false, failover: false, isAvailable: true, network type: 1, apn type: ], networkType=1, inetCondition=100, extraInfo="Barratti_Classica"}]
*** Service (gpsrtns) Create ***
** Service (gpsrtns) Start **
** Service (gpsrtns) Destroy **
** Activity (main) Pause, UserClosed = false **
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
Disregard my last post. I stopped the GPS routine. I'll have to test this with a USB connection instead of the Bridge. When I turn off my internet connection I loose connection with the bridge. Imagine that.

I already set up my phone for Developer and I will be ready to start testing tomorrow.

Now this is all making sense! It should all work after I do that.
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
Well it didn't work after "I did this".

So after getting the debugging with USB setup, which wasn't a picnic. I had to hassle with Windows to install a driver that it wouldn't let me for "security" reasons where I had to download and install gpedit.msc to change a setting. Finally I was able to test. Well I was getting the same result where the ConnectivityChanged event was only getting fired once on startup. After moving the code between the service and main modules with the same results and BTW getting quite frustrated I decided to change the variable names and then it mysteriously started to work. I have no clue as to why but what the hell it worked. Now I have one more thing to figure out and the program is ready for final testing.

Changes:
From -
B4X:
Dim PhoneID As PhoneEvents
Dim PE As PhoneId
...
PE_ConnectivityChanged
To -
B4X:
Dim PES As PhoneEvents
Dim PID As PhoneId
...
PES_ConnectivityChanged
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
Sorry I typed in the above code backwards. I should have typed in this. I need to be more careful.

B4X:
Dim PhoneID As PhoneID
Dim PE As PhonEvents
...
PE_ConnectivityChanged
 
Upvote 0

bocker77

Active Member
Licensed User
Longtime User
OK so it doesn't look like I am stupider than I am, I am going to do this right. Third times a charm as they say. In my defense though its much to early to be typing!

B4X:
Dim PhoneID As PhoneID
Dim PE As PhonEvents
...
PE.InitializeWithPhoneState("PE", PhoneID)
...
PE_ConnectivityChanged
B4X:
Dim PID As PhoneId
Dim PES As PhoneEvents
...
PES.InitializeWithPhoneState("PES", PID)
...
PES_ConnectivityChanged
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…