Android Code Snippet Wifi dis/connection event

This code snippet checks when WIFI will be connect or disconnect. Note that this works only for wifi event, if you want any connection event you should use instead android.net.conn.CONNECTIVITY_CHANGE (in this case this code will not work).
Another note: In some device there is specific issue with multiple message sent from BroadcastReceiver (in my s6edge i got 2 disconnect event, one with bssid and another one without it). To avoid this problem i use "If Not(StartingIntent.HasExtra("bssid")) Then Return", you can also do something like this.

Add this on Manifest
B4X:
AddReceiverText(SendNotification,
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>)
'Send notification is service name

This on service
B4X:
Sub Service_Start (StartingIntent As Intent)
        If StartingIntent.Action = "android.net.wifi.STATE_CHANGE" Then
            Dim jo As JavaObject = StartingIntent
            Dim NetInfo As Object = jo.RunMethodJO("getParcelableExtra",Array("networkInfo")).RunMethod("getDetailedState",Null)
            Dim State As JavaObject : State.InitializeStatic("android.net.NetworkInfo.DetailedState")
            If (NetInfo <> State.GetField("DISCONNECTED") And NetInfo <> State.GetField("CONNECTED") Or (NetInfo = State.GetField("DISCONNECTED") And Not(StartingIntent.HasExtra("bssid")))) Then Return
             LogColor("SentNotification:Service_Start: Connection event: "&NetInfo,Colors.Red)
       end if
 

Attachments

  • WifiListener.zip
    7.5 KB · Views: 357
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
Top