我根据示例实施了bluetouth文件传输:http://developer.android.com/guide/topics/connectivity/bluetooth.html
我遇到了一个问题:当我在大多数情况下传输大型(50-100Mb)文件时 转移过程在转移过程的任何一点都停滞不前。日志信息表示进程在写入(发送方)和读取(接收方)时停止。当卡住时 - 发送方记录到流的总字节数总是超过接收方读取的字节数。减法:收到 - 发送的数据等于4-7 Kb。
似乎在某些时刻,read方法无法进行实际的READ。
有时100Mb传输成功通过。
你可以帮帮我吗? 提前致谢接收方:
try {
BufferedInputStream bis = new BufferedInputStream(mSocket.getInputStream());
File file = new File(root, progressData.file.getFileName());
FileOutputStream fileStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileStream);
DialogsCaller dialog = DialogsCaller.getInstance();
long bytesRead = 0;
int len = 0;
long size = progressData.file.getFileSize();
int bufSize = Constants.BUFFER_SIZE * 8;
byte[] buffer = new byte[bufSize];
int timeOut = 0;
int maxTimeOut = 16;
while (bytesRead < size) {
Log.w(TAG, "BEFORE AVAILABLE " + bytesRead);
while (bis.available() == 0 && timeOut < maxTimeOut) {
timeOut++;
Thread.sleep(250);
}
long remainingSize = size - bytesRead;
int byteCount = (int) Math.min(remainingSize, bufSize);
Log.w(TAG, "BEFORE READ " + "currentSize : "
+ bytesRead + " byteCount " + byteCount);
len = bis.read(buffer, 0, byteCount);
Log.w(TAG, "AFTER READ " + "Len " + len);
if (len > 0) {
timeOut = 0;
Log.w(TAG, "BEFORE WRITE " + bytesRead);
bos.write(buffer, 0, len);
bytesRead += len;
Log.w(TAG, "AFTER WRITE " + bytesRead);
dialog.setProgress(
progressData, (int) bytesRead);
}
}
bos.flush();
} catch (Exception e) {
Callback.post(e);
Log.e(TAG, "Receiving problem");
mHandler.obtainMessage(MessageType.CANNOT_RECEIVE_DATA)
.sendToTarget();
throw e;
} finally {
if (bos != null) {
try {
Log.i(TAG, "FILE CLOSE");
bos.close();
} catch (IOException e) {
Callback.post(e);
}
}
}
发件人:
try {
File file = new File(progressData.file.getFilePath());
FileInputStream fileStream = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fileStream);
BufferedOutputStream bos = new BufferedOutputStream(
mCurrentSocket.getOutputStream());
long sentBytes = 0;
int len = 0;
byte[] buffer = new byte[Constants.BUFFER_SIZE];
DialogsCaller dialog = DialogsCaller.getInstance();
while ((len = bis.read(buffer)) > -1) {
if (len > 0) {
Log.w("F_" + TAG, "BEFORE " + "currentSize : " + sentBytes
+ "Len " + len);
bos.write(buffer, 0, len);
bos.flush();
sentBytes += len;
Log.w("F_" + TAG, "AFTER " + "currentSize : " + sentBytes);
dialog.setProgress(progressData, (int) sentBytes);
// SystemClock.sleep(120);
}
}
} catch (Exception e2) {
Callback.post(e2);
Log.e(TAG, "Sending problem");
mHandler.obtainMessage(MessageType.CANNOT_SEND_DATA).sendToTarget();
throw e2;
} finally {
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
Callback.post(e);
Log.e(TAG, "Stream not closed");
}
}
答案 0 :(得分:0)
您可以在发送数据时节流...在发送下一个数据块之前延迟几毫秒。还要根据目标设备减少缓冲区大小。我遇到了类似的问题。调整缓冲区大小后它基于目标设备工作。您将必须实现一些逻辑来获取目标设备。
android中的blutooth通信是不稳定的(因为不同的无线电和实现)你必须尝试不同的东西才能开始在所有设备上正常工作。