我正在尝试使用RFCOM服务器套接字通过蓝牙发送任何文本或图像/音频文件。我使用以下代码
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkBTPermissions();
// byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
// mBluetoothConnection.write(bytes);
file_permission();
// byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
File myfile = new File("/sdcard/bluetooth/tom.txt");
byte[] bytes= new byte[(int)myfile.length()];
Log.d(TAG,"file length() =" + (int)myfile.length());
try {
FileInputStream fis = new FileInputStream(myfile);
BufferedInputStream bis = new BufferedInputStream(fis,(int)myfile.length());
//bis.read(bytes,0,bytes.length);
Log.d(TAG,"fis created");
// FileInputStream
mBluetoothConnection.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
在这里,我能够发送我的文本文件的内容,甚至能够接收。 接收者代码:
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
我的问题如何将我的文件作为一个整体发送到接收器并接收并保存?。在各种教程中我只发现如何通过蓝牙发送文本。请帮忙。