Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim UDPSocket1 As UDPSocket   
    Dim Tablet As Reflector
    Dim Device As Phone
    Dim ServerIndex As Int = -1
    Dim RequestIP As Boolean = True
    Dim UDPPort As Int = 4444
End Sub
Sub Service_Create
    Tablet.Target = Tablet.GetContext
    Tablet.Target = Tablet.RunMethod2("getSystemService", "wifi", "java.lang.String")
    Tablet.Target = Tablet.RunMethod2("createMulticastLock", "mylock", "java.lang.String")
    Tablet.RunMethod2("setReferenceCounted", False, "java.lang.boolean")     'not really necessary but safer
    Tablet.RunMethod("acquire")                                            'acquire the lock
    UDPSocket1.Initialize("UDP", UDPPort, 128)    'Port and buffer size can be changed
'    ToastMessageShow("Port " & UDPPort & " initialized.",True)
End Sub
Sub Service_Start (StartingIntent As Intent)
    SendMYID
End Sub
Sub SendMYID
    If RequestIP = True Then
        RequestIP = False
        UDPSendMsg("MYID:~" & ServerIndex & "~" & Main.version.SerialNo & "~" & Main.LicenseData.GroupCode & "~" & _
                    Main.CS.FacilityID & " " & Main.licensedata.Addr1 & " " & Main.LicenseData.City & ", " & Main.LicenseData.state, "255.255.255.255")
    End If
End Sub
'send the host a UDP message
Sub UDPSendMsg(msg As String, IPAddr As String)
Log("        Sending: " & msg)
    Dim Packet As UDPPacket
    Dim data() As Byte  
    data = msg.GetBytes("UTF8")
    Packet.Initialize(data, IPAddr, UDPPort)    'IP and Port can be changed
    UDPSocket1.Send(Packet)
End Sub
'Host requested our info
Sub UDP_PacketArrived (Packet As UDPPacket)
    Dim msg As String
    msg = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
    Dim IP As String = Packet.HostAddress
    Dim parts() As String = Regex.Split("~", msg)
    If parts.Length >= 3 Then
        Select Case parts(0)
            Case "UDPS:"                    'this is a legitimate "here is my ip/port" request from server
Fn.Logit("        Receiving: " & msg)
                Main.TCP.IPAddress = parts(2)
                Main.TCP.Port = parts(3)
                XMLBuilder.SaveIPProfile
                StopService("")
            Case "UDPR:"
Fn.Logit("        Receiving: " & msg)
                Main.TCP.IPAddress = parts(2)
                Main.TCP.Port = parts(3)
                XMLBuilder.SaveIPProfile
                ServerIndex = parts(1)
                SendMYID
                StopService("")
        Case Else                            'other broadcast datagram, don't terminate
        End Select
    End If
End Sub
Sub Service_Destroy
    UDPSocket1.Close
    Tablet.RunMethod("release")                        ' release when not needed to save battery    
End Sub