我正在尝试通过蓝牙在Android设备上发送文件。我做了发现,连接并制作了一个蓝牙插座。问题是当我在蓝牙套接字的输出流中写字节数组时,接收端虽然接受正在发送的内容但没有收到任何内容。
以下是我正在做的事情(蓝牙适配器不好)
请告知。
try
{
BluetoothDevice dev = bad.getRemoteDevice(a);
bad.cancelDiscovery();
dev.createRfcommSocketToServiceRecord(new UUID(1111, 2222));
Method m = dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
bs = (BluetoothSocket) m.invoke(dev, Integer.valueOf(1));
bs.connect();
tmpOut = bs.getOutputStream();
}catch(Exception e)
{
}
File f = new File(filename);
byte b[] = new byte[(int) f.length()];
try
{
FileInputStream fileInputStream = new FileInputStream(f);
fileInputStream.read(b);
}catch(IOException e)
{
Log.d(TAG, "Error converting file");
Log.d(TAG, e.getMessage());
}
try {
tmpOut.write(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:3)
我使用下面的代码剪断连接到远程蓝牙设备中的串行服务,它对我来说很好。只需确保其他设备(可以是移动设备或PC)具有用于通过蓝牙进行串行通信的服务器插槽(请参阅下面的服务器端代码)
客户端:
UUID serialUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice btDevice = btAdapter.getRemoteDevice(BTAddress); // Get the BTAddress after scan
BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(SERIAL_UUID);
btSocket.connect();
InputStream iStream = btSocket.getInputStream();
OutputStream oStream = btSocket.getOutputStream();
服务器端:
UUID serialUUID = new UUID("1101", true);
String serviceURL = "btspp://localhost:" + serialUUID
+ ";name=Android BT Server;authorize=false;authenticate=false";
StreamConnectionNotifier connectionNotifier = (StreamConnectionNotifier) Connector
.open(serviceURL);
// Blocking method will wait for client to connect
StreamConnection connection = connectionNotifier.acceptAndOpen();
RemoteDevice remoteDevice = RemoteDevice.getRemoteDevice(connection);
InputStream btInput = connection.openInputStream();
OutputStream btOutput = connection.openOutputStream();
答案 1 :(得分:1)
为什么不使用标准的api调用而不是通过反射调用,例如:
BluetoothSocket socket = destination
.createRfcommSocketToServiceRecord(new UUID(...)) ;
你的捕获块也是空的。你确定套接字没有任何例外吗?如果由于某种原因连接失败,Connect将抛出IOException。见link
答案 2 :(得分:0)
可能是因为dev和bs在使用tmpout之前超出了范围,因为它们是在try / catch块中声明的。