【发布时间】:2014-08-15 22:39:43
【问题描述】:
我已经按照例子实现了蓝牙文件传输: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");
}
}
【问题讨论】: