我正在创建一个使用蓝牙连接与 PC 通信的 Android 应用程序。我正在尝试将 ArrayList 中的项目从 PC 发送到 Android。
问问题
1313 次
2 回答
0
尝试刷新输出流并关闭输出流。这应该将缓冲区中的剩余数据刷新到 Android 设备。此外,您需要为每个输出添加一个新的换行符(如果 ArrayList 的值中不存在一个),即在您的 PC 代码上执行以下操作:
PC Code:
list = FilterFile.aList;
for(int z = 0; z < list.size(); z++) {
int a = list.size();
System.out.println("in for\n"+list.size());
String str = list.get(z);
System.out.println(str);
out.write((str+"\n").getBytes());
out.flush();
}
out.close();
Android (Client) side code:
public class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private InputStream mmInStream = null;
public OutputStream mmOutStream = null;
private static final String TAG = "ConnectedThread";
private static final boolean D = true;
int i;
char a;
String line;
String y = "";
//DataInputStream din=null;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
//din = new DataInputStream(mmInStream);
if (D) Log.e(TAG, "-- in connected() --");
}
public void run() {
if (D) Log.e(TAG, "-- ConnectedThread --");
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public String readList() {
String data = "";
try {
byte buff[] = new byte[1024];
int count = -1;
while((count = mmInStream.read(buff, 0, 1024)) != -1){
data += new String(buff,0,count);
}
String lines[] = data.split("\n");
for(int i = 0; i < lines.length; i++){
//this will print your individual lines...
System.out.println(lines[i]);
}
} catch (Exception e) {
///print your error message here
}
finally{
if(in != null){
try {
mmInStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return data;
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
于 2013-04-02T13:55:32.933 回答
-1
尝试只调用write
一次该方法(并在调用后刷新/关闭缓冲区):
String str = "";
for(int z = 0; z < list.size(); z++) {
str += list.get(z);
}
System.out.println(str);
out.write(str.getBytes());
out.flush();
out.close();
于 2013-04-02T13:55:50.547 回答