我是Android初学者,接收RfcommSocket从蓝牙发送的数据流并将其添加到LinkedHashMap有问题?我使用下面的代码,但它不起作用,我不知道,我该如何处理呢?
public class BluetoothConnectionThread extends Thread{
public static final int MESSAGE_READ = 9999;
private final BluetoothDevice btDevice;
private BluetoothSocket btSocket;
private InputStream inStream;
private OutputStream outStream;
Map<Integer, Byte[]> linkedHashMap = new LinkedHashMap<Integer, Byte[]>();
private static UUID uuid = UUID.fromString("ae3fdfc0-8bd1-11e5-8994-feff819cdc9f");
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String address = null;
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
public BluetoothConnectionThread(BluetoothDevice device) {
this.btDevice = device;
try
{
btSocket = this.btDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException ex) {
btSocket = null;
}
}
public void ConnectedThread(BluetoothSocket socket) {
this.btSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
inStream = tmpIn;
outStream = tmpOut;
}
public void run() {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
byte[] buffer = new byte[32];
int bytes;
try {
btSocket.connect();
bytes = inStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch(IOException ex) {
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
btSocket.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
为了回答它无法正常工作的原因,您不会向hashmap添加任何值。
根据您选择键Integer的方式,我刚刚使用静态int进行演示,但这不是解决此问题的最佳方法。如果这是您生成密钥的方式,我建议使用List。
static int intKey = 0;
在case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
linkedHashMap .put(intKey, readBuf)
intKey++;
我建议您检查其他方法,或者您似乎并不清楚如何或为何使用链接哈希映射。