简体   繁体   中英

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();
}

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM