美好的一天所有,根据我之前提出的问题,我已经能够将文件转换为字节数组,以便使用此方法使用write方法:
public void sendFile(){
Log.d(TAG, "sending data");
InputStream inputStream = null;
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "" + filesID.get(0));
Log.d(TAG, "obtained input stream here in recentDevices Activity");
try {
inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int len = 0;
while((len = inputStream.read(buffer)) != -1){
byteBuffer.write(buffer, 0, len);
}
Log.d(TAG, "sending data to connected thread");
bluetooth_service.write(byteBuffer.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
并且从BluetoothChatService示例中我在连接的线程中有这个写入方法:
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
r = connectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes); // basically stuck here. nothing happens here
} catch (IOException e) { }
mHandler.sendEmptyMessage(RecentDevices.TRANSFER_COMPLETED);
}
基本上卡在连接线程的write方法中,似乎没有发生任何事情。在处理程序发送TRANSFER_COMPLETED方法之后,我放了一个进度对话框来解除它,但程序只是卡在这里。尝试过发送到电脑或其他Android设备。没运气!任何人都有成功或有解决方案吗?
答案 0 :(得分:2)
您的读输入流方法怎么样?
基于SO上的很多帖子,我使用此代码来读取输入流:
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
int bytesRead = -1;
String message = "";
if (mmInStream.available() > 0) {
bytesRead = mmInStream.read(buffer);
if (bytesRead > 0) {
while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = mmInStream.read(buffer);
}
if((buffer[bytesRead - 1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
} else {
message = message + new String(buffer, 0, bytesRead - 1);
}
mHandler.obtainMessage(ViewContactList.MESSAGE_READ, message.getBytes().length, -1, message).sendToTarget();
}
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost(e.getMessage());
break;
}
}
}
在ConnectedThread
的{{1}}内进行试用。