作者fake01 (code)
看板AndroidDev
标题Re: [问题] 蓝芽接值 掉值问题
时间Fri Feb 1 02:14:50 2013
※ 引述《fake01 (code)》之铭言:
: 使用手机蓝芽接值,而接的值是由硬体端不断丢值,
: 通常一秒丢一串字串 例如 123$456# or 455$123$
: 但是蓝芽这边接一次有时候会漏掉值 123456# 或 123$56,
: 但有时候又会正常接,是无法判断硬体这边丢一次的字串是甚麽,
: 请问该如何解决呢
: case MESSAGE_READ:
: byte[] readBuf = (byte[]) msg.obj;
: // construct a string from the valid bytes in the buffer
: String readMessage = null;
: try {
: readMessage = new String(readBuf, 0,msg.arg1,"GBK");
: }
: catch (UnsupportedEncodingException e)
: {
: // TODO Auto-generated catch block
: e.printStackTrace();
: }
: break;
: // 以上就是蓝芽抓值的code,麻烦各位了
因为C大说贴socket部分的code
会比较好懂,我是用Chat? 那个蓝芽范例所改的应该没甚麽问题
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(TestbtActivity.MESSAGE_READ,
bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.58.82.128
1F:推 MetalChao:我不知道你掉值的问题在哪, 不过对於你的code有几点想法 02/01 20:09
2F:→ MetalChao:1. 你的值内容是什麽样子? 为什麽要用 GBK encoding? 02/01 20:10
3F:→ MetalChao:2. constructor 如果真的有 io exception, 你只是忽略掉 02/01 20:11
4F:→ MetalChao:那麽接下来的 run 里就会有 null pointer exception 02/01 20:12
5F:→ MetalChao:3. tmpIn tmpOut 这两个变数是不需要的 02/01 20:12
6F:→ fake01:掉直就像是应该要给123#456 变成 #456 或 56 02/02 00:11
7F:→ fake01:因为传值端丢过来的值要用GBK才看得懂 02/02 00:11