2011-07-03 113 views
5

我花了一些时间研究Android与蓝牙设备通信的能力,蓝牙设备旨在通过PC上的蓝牙COM端口进行通信。我一直无法找到明确的答案,所以我想我会在这里问。我想确保这可能与Android。Android蓝牙COM端口

我是蓝牙通信的新手,但迄今为止我所做的研究让我感到RFCOMM有点像我想要的。不幸的是,我仍然无法证实这实际上是可能的。

任何帮助/资源将不胜感激。

+0

它是如何设计,以通过蓝牙串口通信? com端口在PC上,我假设的蓝牙设备不是,而是连接到PC。 –

+0

所以我并不完全确定,蓝牙设备的指示说要通过蓝牙COM端口进行配对。有什么具体的我应该寻找?就像我说的,仍然试图围绕这个东西包裹我的头。 –

+0

只要尝试编写代码来配对设备,看看会发生什么。 –

回答

11

是的,Android可以连接到PC上的蓝牙COM端口。我目前正在开发这样的应用程序。下面是一个代码示例(ITE需要蓝牙权限TE在Manifest.xml文件中设置):

<uses-permission android:name="android.permission.BLUETOOTH" /> 

的Java:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 
if (adapter == null) { 
    // Device does not support Bluetooth 
    finish(); //exit 
} 

if (!adapter.isEnabled()) { 
//make sure the device's bluetooth is enabled 
    Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
    startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT); 
} 

final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection 
mac = "00:15:83:3D:0A:57"; //my laptop's mac adress 
device = adapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired 


// Get a BluetoothSocket to connect with the given BluetoothDevice 
BluetoothSocket socket = null; 
OutputStream out = null; 
try { 
    socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID); 
} catch (IOException e) {} 

try {   
    socket.connect(); 
    out = socket.getOutputStream(); 
    //now you can use out to send output via out.write 
} catch (IOException e) {} 
+0

如果我需要处理使用BluetoothSocket在套接字上读/写的超时,那么该怎么办?我正在开发一个使用您的方法进行连接的Android应用程序,但我仍然无法处理时间,这非常重要,因为我的远程蓝牙设备有点特别。 – Sonhja

+0

我曾经自己做过,但这里描述的方法可能有所帮助:http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html和http://developer.android.com/reference/android/bluetooth/ BluetoothSocket.html#isConnected() – Konsalik

+0

我试过你的代码,但我有这个异常调用连接: java.io.IOException:读取失败,套接字可能关闭或超时,在android.bluetooth.BluetoothSocket读取ret:-1。 readAll(BluetoothSocket.java:637) – devmao