我正在尝试使用这些来源使文件传输蓝牙应用工作:
http://developer.android.com/guide/topics/connectivity/bluetooth.html
当我尝试以这种方式使用 InputStream.read()
方法获取 InputStream 字节时:
public class ConnectedThread extends Thread {
...(some code here)
public void run(){
byte[] buffer = new byte[1024];
int bytes = -1;
//Keep listening to the InputStream while connected
while (true){
try {
bytes = this.mmInStream.read(buffer);
//* this part is not reached
if (bytes==-1){
Log.d("NoData:","-1");
}
}
catch(Exception e){
Log.d("inStream exception:",e.getMessage());
break;
}
}
}
...(some code here)
}
代码的下一部分(在本例中为 “if”
部分)永远不会到达,也不会到达 Log.D
调试输出或我在下面放置的任何其他内容.我刚从 LogCat 收到这条消息:
BluetoothSocket read in: android.net.LocalStocketImpl$SocketInputStream@f7e
b08 len: 1024
要将数据从客户端传输到服务器,我这样做:
public class MainActivity extends Activity {
...(some code here)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientConnect();
//serverConnect();
}
...(some code here)
public void clientConnect(){
Set<BluetoothDevice> devices;
devices = bConfig.getPairedDevices();
if (devices == null){
return;
}
if (devices.size() > 0) {
BluetoothDevice device = devices.iterator().next();
ConnectThread connectTransmit = new ConnectThread(device,bConfig.getBluetoothAdapter(),BluetoothConfig.mUUID);
connectTransmit.start();
Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show();
socket = connectTransmit.mmSocket;
ConnectedThread connectedThread = new ConnectedThread(socket);
//write file bytes to the connected thread, so the thread can receive its own input written bytes later
File file_to_transfer = new File(Environment.getExternalStorageDirectory() + "/txtTransfer.txt");
//get bytes from our File
int size = (int) file_to_transfer.length();
byte[] bytes = new byte[size];
try {
//14b are read succesfully, the whole text file
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file_to_transfer));
buf.read(bytes,0,bytes.length);
buf.close();
}catch (FileNotFoundException e){
Log.d("FileNotFoundException:",e.getMessage());
}catch (IOException e){
Log.d("IOException:",e.getMessage());
}
//send the data to the server
connectedThread.start();
connectedThread.write(bytes);
//connectedThread.cancel();
}
}
...(some code here)
}
AcceptThread
(实现的服务器部分)有效,因为当我运行客户端部分连接然后传输数据时,在设备中调试时服务器部分上的 LogCat 激活并到达线程的 run 方法,我在其中调用 ConnectedThread
实现,但在它“显然”读取字节之后,它卡在了 LogCat 上,没有错误。
请告诉我如何才能完成读取字节以移动到流程的下一部分。
谢谢
最佳答案
您被阻止等待更多输入。
标记为...(此处为一些代码)
的部分应该在读取循环内, 在流结束测试之后。注意:如果 read()
返回 -1,这并不意味着“无数据”,它意味着流结束,您应该关闭套接字并跳出读取循环。否则,您应该继续处理刚刚读取的数据。目前你只是读取并忽略所有输入,直到流结束,这是没有意义的。您充其量只能处理最后的部分缓冲区,而且您不会知道它有多长。
关于java - 蓝牙传输应用程序在使用 InputStream.read() 后停止,没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165776/