问题
I am trying to send a file over bluetooth in an android device. I have done discovery, connection and have made a bluetooth socket. Problem is when i am writing the byte array in the output stream of the bluetooth socket, the recieving side does not receive anything although it accept that something is being sent.
Here's what Iam doing (bad is the bluetooth adaptor)
Please advise.
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();
}
回答1:
I am using the below code snipped to connect to the serial service in a remote Bluetooth device and it is working fine for me. Just make sure that the other device (can be mobile or PC) has a server socket for serial communication over Bluetooth (see the server side code below)
Client Side:
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();
Server Side:
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();
回答2:
Why not use the standard api call instead of calling through reflection, eg:
BluetoothSocket socket = destination
.createRfcommSocketToServiceRecord(new UUID(...)) ;
Also your catch block is empty. Are you sure the socket was connected without any exception? Connect will throw IOException if the connection failed for some reason. See this link
回答3:
It might be because dev and bs go out of scope before tmpout is used because they are declared within your try/catch block.
来源:https://stackoverflow.com/questions/11502497/android-bluetooth-file-sending