I'm trying to send data through a BluetoothSocket between two Android tablets. I've created one using 'createRfcommSocketToServiceRecord', and on both devices 'isConnected()' returns True and 'getRemoteDevice().getName()' returns with the other device, as desired. However, when I try to send and receive data between them, nothing is received on either end. In the Android documentation for BluetoothAdapter(link), it states:
Use BluetoothDevice#createRfcommSocketToServiceRecord to connect to this socket from another device using the same UUID.
I've tried running the code at the bottom on both devices. I've also tried running:
server = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord('TestServer', UUID.fromString("00001105-0000-1000-8000-00805f9b34fb"))
client, address = server.accept()
... On one device and the code at the bottom on the other device, which leads to the ServerSocket just hanging on accept() indefinitely even after attempting to connect to it on the other device. I think I'm doing something fundamentally wrong but I've been scouring the Android developer docs for a while and I can't figure out what my misunderstanding is. Any enlightenment would be thoroughly appreciated.
I'm using Kivy to create a text field for sending some test data, but I've simplified it here.
import threading
import time
from jnius import autoclass
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
BluetoothServerSocket = autoclass('android.bluetooth.BluetoothServerSocket')
UUID = autoclass('java.util.UUID')
socket = None
for device in BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray():
if 'Galaxy Tab' in device.getName():
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001105-0000-1000-8000-00805f9b34fb"))
in_stream = socket.getInputStream()
out_stream = socket.getOutputStream()
socket.connect()
break
def receive(self, instance=None):
while True:
time.sleep(0.5)
out_stream.write('test'.encode())
out_stream.flush()
print(in_stream.read())
threading.Thread(target=receive).start()