milan7
milan7

Reputation: 65

How to receive data using Bluetooth Server Socket RFCOMM in Android?

I am trying to make an android application that receives and display the data coming from a paired Bluetooth device. I have a working python code and I want to write the similar code in android.I can run Python in Android phone but no UI! The code find the port using RFCOMM and then connects using socket .The address of the Bluetooth device is in XX:XX:XX:XX:XX:XX format and I am not sure how to write the code for android.Would appreciate it if you help me! Thanks! Here is my python code:

from bluetooth import *
from sys import stdout

server_address = "XX:XX:XX:XX:XX:XX"
#port = get_available_port( RFCOMM )
try:
  my=sock
except:
  sock=BluetoothSocket( RFCOMM )
  sock.connect((server_address, 1))
  print "connected"
else:
  print "---"
  data=0
while 1:
data= sock.recv(1)
if data== '':
  print "Socket broken"
else:
  data= data
  print "received"
  print text 

sock.close()
sock=None
del sock

Can this android code help?

String deviceAddress = "XX:XX:XX:XX:XX:XX";
adapter = BluetoothAdapter.getDefaultAdapter();

BluetoothDevice device = _adapter.getRemoteDevice(deviceAddress);

try {
    socket = device.createRfcommSocketToServiceRecord(BluetoothSerialUuid);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

try {
    socket.connect();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 0

Views: 9104

Answers (1)

J.K
J.K

Reputation: 2393

You can find the full source code for this sample in your SDK at:

<sdk>/platforms/android-<version>/samples/

which has name BLUETOOTH CHAT see that code and filter what you want :)

Upvotes: 1

Related Questions