use*_*785 6 sockets android bluetooth
嗨,我正在尝试创建一个 Android 应用程序,该应用程序将连接到我想向其发送数据的 Blue SMiRF 蓝牙加密狗。我已经阅读了开发人员页面并查看了多个不同的示例,但是我目前无法创建到套接字的连接。代码的蓝牙部分几乎来自我能够找到的示例。当尝试连接到蓝牙加密狗时,应用程序会强制关闭,因为我没有正确处理一些错误。但是,我也尝试使用该应用程序只是为了连接到另一台 PC,并且由于某种原因无法正确建立连接,即使在运行该应用程序之前我已经通过蓝牙设置与设备配对。我在下面发布了一些更重要的代码,用于说明我认为我的问题可能出在哪里。
protected void connect(BluetoothDevice device) {
//BluetoothSocket socket = null;
try {
//Create a Socket connection: need the server's UUID number of registered
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
socket.connect();
Log.d("EF-BTBee", ">>Client connectted");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });
new Thread() {
public void run() {
while(true)
{
try {
Log.d("EF-BTBee", ">>Send data thread!");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa2, 0, 7, 16, 0, 4, 0 });
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
};
}.start();
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
} finally {
if (socket != null) {
try {
Log.d("EF-BTBee", ">>Client Close");
socket.close();
finish();
return ;
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
}
}`
Run Code Online (Sandbox Code Playgroud)
我也试过使用
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
Run Code Online (Sandbox Code Playgroud)
而不仅仅是上面的“socket =”行,但仍然没有成功。
如果设备已经配对,那么您可以使用
if(device.getBondState()==device.BOND_BONDED){
Log.d(TAG,device.getName());
//BluetoothSocket mSocket=null;
try {
mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG,"socket not created");
e1.printStackTrace();
}
try{
mSocket.connect();
}
catch(IOException e){
try {
mSocket.close();
Log.d(TAG,"Cannot connect");
} catch (IOException e1) {
Log.d(TAG,"Socket not closed");
e1.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
供 MY_UUID 使用
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42037 次 |
| 最近记录: |