Home > Back-end >  How to effectively connect to Bluetooth Device socket with Android Java?
How to effectively connect to Bluetooth Device socket with Android Java?

Time:06-08

I am trying to connect my bluetooth app to my PC using Android Java. After I have connected my app to the PC socket then I can send a message such as Say Hello. My app is successful in scanning for Bluetooth Devices in range using the location and bluetooth API. It discovers my PC and I grab the UUID of my PC from the Bluetooth Device profile discovered for my PC. I expose the UUID of my PC as a Bluetooth Device on the logcat and it looks like device.getUUIDs does not return null as long as you cancel discovery before calling it. Here is the UUID string printed on my logcat

BluetoothClient.BluetoothClient D/UUID: 0000110a-0000-1000-8000-00805f9b34fb

The code below shows how I attempt to connect to the PC Bluetooth device socket

//check if the device is already bonded and attempt to connect to its socket if it is exposed
 if (dev.BondState == Bond.Bonded){
  //device is a bluetooth device on my list I grabbed from the broadcast receiver
  //grab the UUID of the discovered bluetooth device
  UUID MYUUID = dev.GetUuids()[0].Uuid;
  //create a bluetooth socket using the UUID for connection purposes
  BluetoothSocket socket = dev.CreateRfcommSocketToServiceRecord(MYUUID);
  //connect to the socket
  socket.Connect();
 } 

The code written does not throw any exceptions nor does the app crash, this information is printed on my logcat.

 D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
 // I do not know what the above is and what device is null 
 I/BluetoothSocket: connect() for device F894C2 called by pid: 2822
 W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
 //if a bluetooth manager callback is needed for the socket creation, how do attach the callback to my code to make this work, Thank You.

CodePudding user response:

See section 5.5.3 in the README.md documentation here for bare-bones code https://github.com/petzval/btferret. The functions instream.read and outstream.write exchange serial data.

 byte[] dat;
 String s;
 int len;

 dat = new byte[32];
 s = "Hello";
 len = s.length();
 for(n = 0 ; n < len ;  n)
   dat[n] = s.charAt(n);
 
 outstream.write(dat,0,len);
  • Related