...hier noch mal das Tutorial von Erel "Android-Bluetooth / BluetoothAdmin-Tutorial" leicht abgeändert für die Verbindung von mehr als zwei Geräten...
Main (geändert)
…und BluetoothManager (geändert)
Main (geändert)
B4X:
#Region Module Attributes
#FullScreen: False
#IncludeTitle: True
#ApplicationLabel: Bluetooth Example
#VersionCode: 1
#VersionName:
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#End Region
#BridgeLogger: true
Sub Process_Globals
Private rp As RuntimePermissions
Public status As Int
End Sub
Sub Globals
Private btnSearchForDevices As Button
Private btnAllowConnection As Button
Public btnMultiConnection As Button
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
End Sub
Sub Activity_Resume
UpdateState
End Sub
Public Sub UpdateState
btnSearchForDevices.Enabled = Starter.Manager.BluetoothState
btnAllowConnection.Enabled = Starter.Manager.BluetoothState
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub btnSearchForDevices_Click
rp.CheckAndRequest(rp.PERMISSION_ACCESS_COARSE_LOCATION)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result = False Then
ToastMessageShow("No permission...", False)
Return
End If
Dim success As Boolean = Starter.Manager.SearchForDevices
If success = False Then
ToastMessageShow("Error starting discovery process.", True)
Else
ProgressDialogShow2("Searching for devices...", False)
End If
End Sub
Public Sub DiscoverFinished
ProgressDialogHide
If Starter.Manager.foundDevices.Size = 0 Then
ToastMessageShow("No device found.", True)
Else
Dim l As List
l.Initialize
For Each nm As NameAndMac In Starter.Manager.foundDevices
l.Add(nm.Name)
Next
InputListAsync(l, "Choose device to connect", -1, True)
Wait For InputList_Result (Index As Int)
If Index <> DialogResponse.CANCEL Then
Dim device As NameAndMac = Starter.Manager.foundDevices.Get(Index)
Starter.Manager.ConnectTo(device)
ProgressDialogShow2($"Trying to connect to: ${device.Name} (${device.Mac})"$, False)
End If
End If
End Sub
Public Sub AfterConnect (Success As Boolean)
ProgressDialogHide
End Sub
Sub btnAllowConnection_Click
Starter.Manager.ListenForConnections
btnMultiConnection.Text = "2 Geräte"
btnMultiConnection.Tag = 0
status = 0
End Sub
Public Sub btnMultiConnection_Click
If btnMultiConnection.Text = "2 Geräte" Then
btnMultiConnection.Text = "3 + mehr Geräte"
btnMultiConnection.Tag = 1
status = 1
Else
btnMultiConnection.Text = "2 Geräte"
btnMultiConnection.Tag = 0
status = 0
End If
End Sub
…und BluetoothManager (geändert)
B4X:
Sub Class_Globals
Private AStream As AsyncStreams
Private AStream1 As AsyncStreams
Private serial As Serial
Private serial1 As Serial
Private admin As BluetoothAdmin
Public foundDevices As List
Type NameAndMac (Name As String, Mac As String)
Public BluetoothState, ConnectionState As Boolean
Dim x As Int
End Sub
Public Sub Initialize
admin.Initialize("admin")
serial.Initialize("serial")
serial1.Initialize("serial1")
If admin.IsEnabled = False Then
If admin.Enable = False Then
ToastMessageShow("Error enabling Bluetooth adapter.", True)
Else
ToastMessageShow("Enabling Bluetooth adapter...", False)
End If
Else
BluetoothState = True
End If
End Sub
Private Sub Admin_StateChanged (NewState As Int, OldState As Int)
Log("state changed: " & NewState)
BluetoothState = NewState = admin.STATE_ON
NotifyOfStateChanged
End Sub
Public Sub ConnectTo (Device As NameAndMac)
ToastMessageShow(x,True)
If x = 0 Then
serial.Connect(Device.Mac)
Else
serial1.Connect(Device.Mac)
End If
End Sub
Private Sub Serial_Connected (Success As Boolean)
Log("connected: " & Success)
CallSub2(Main, "AfterConnect", Success) 'allow the activity to hide the dialog
ConnectionState = Success
If Success = False Then
Log(LastException.Message)
ToastMessageShow("Error connecting: " & LastException.Message, True)
Else
If AStream.IsInitialized Then AStream.Close
'prefix mode! Change to non-prefix mode if communicating with non-B4X device.
AStream.InitializePrefix(serial.InputStream, False, serial.OutputStream, "astream")
If Main.status = 1 Then
CallSub(Main,"btnSearchForDevices_Click")
Else
StartActivity(ChatActivity)
End If
X = 1
End If
NotifyOfStateChanged
End Sub
Private Sub Serial1_Connected (Success As Boolean)
Log("connected: " & Success)
CallSub2(Main, "AfterConnect", Success) 'allow the activity to hide the dialog
ConnectionState = Success
If Success = False Then
Log(LastException.Message)
ToastMessageShow("Error connecting: " & LastException.Message, True)
Else
If AStream1.IsInitialized Then AStream1.Close
'prefix mode! Change to non-prefix mode if communicating with non-B4X device.
AStream1.InitializePrefix(serial1.InputStream, False, serial1.OutputStream, "astream1")
StartActivity(ChatActivity)
X = 0
End If
NotifyOfStateChanged
End Sub
Public Sub SendMessage (msg As String)
AStream.Write(msg.GetBytes("utf8"))
AStream1.Write(msg.GetBytes("utf8"))
End Sub
Private Sub AStream_NewData (Buffer() As Byte)
CallSub2(ChatActivity, "NewMessage", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub
Private Sub AStream1_NewData (Buffer() As Byte)
CallSub2(ChatActivity, "NewMessage", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub
Private Sub AStream_Error
ToastMessageShow("Connection is broken.", True)
ConnectionState = False
NotifyOfStateChanged
End Sub
Private Sub AStream1_Error
ToastMessageShow("Connection is broken.", True)
ConnectionState = False
NotifyOfStateChanged
End Sub
Private Sub AStream_Terminated
AStream_Error
End Sub
Public Sub Disconnect
If AStream.IsInitialized Then AStream.Close
serial.Disconnect
If AStream1.IsInitialized Then AStream1.Close
serial1.Disconnect
End Sub
Public Sub SearchForDevices As Boolean
foundDevices.Initialize
Return admin.StartDiscovery
End Sub
Private Sub Admin_DiscoveryFinished
CallSub(Main, "DiscoverFinished")
End Sub
Private Sub Admin_DeviceFound (Name As String, MacAddress As String)
Log(Name & ":" & MacAddress)
Dim nm As NameAndMac
nm.Name = Name
nm.Mac = MacAddress
foundDevices.Add(nm)
End Sub
Public Sub ListenForConnections
'this intent makes the device discoverable for 300 seconds.
Dim i As Intent
i.Initialize("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE", "")
i.PutExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300)
StartActivity(i)
serial.Listen
serial1.Listen
End Sub
Private Sub NotifyOfStateChanged
For Each Target In Array(Main, ChatActivity)
CallSub(Target, "UpdateState")
Next
End Sub