我正在尝试通过使用蓝牙MAC地址在特定设备上通过蓝牙发送多个图像文件: 以下是将字节数组发送到套接字的代码:
ArrayList<Uri> uris = new ArrayList<Uri>();
for (int j = 0; j < imagesList.size(); j++) {
File file = new File(imagesList.get(j));
// uris.add(Uri.fromFile(file))
uris.add(FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".my.package.name.provider", file));
for(int k=0;k<1;k++){
byte[] send = readBytes(uris.get(position));
Bitmap bitmap = BitmapFactory.decodeByteArray(send, 0, send.length);
chatService.write(send);// calling write method of thread in for loop
}
}
}
以下是输入和输出流的连接线程类:
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tmpIn;
outputStream = tmpOut;
public void run() {
try {
byte[] buffer = new byte[1024 * 4];
int bytes;
fileName= new SimpleDateFormat("yyyyMMdd-HHmmss'.jpg'").format(new Date());
FileOutputStream output = new FileOutputStream("/sdcard/"+fileName);
//FileOutputStream output = new FileOutputStream("/sdcard/picfling.jpg");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.close();
}catch (Exception e){e.printStackTrace();}
}
// write to OutputStream
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
}
}
}
我可以通过此代码传输单个图像,但是在多个图像的情况下它不起作用。例如,如果我在for loop中调用connectedThread Class的write方法。