android上实现蓝牙透传时遇到点问题

调试android SDK附带的示例BluetoothChat。在BluetoothChat的基础上实现手机蓝牙和HC-6蓝牙模块建立连接,借此通道和PC上的串口调试工具通信——实现蓝牙透传功能。

 

(1)调试BluetoothChat时,不能和HC-6蓝牙模块建立连接,折腾了几个小时发现是UUID的问题。

// BluetoothChat里的UUID没有用,改为BTClient里的UUID才OK
private static final UUID MY_UUID = 
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//"fa87c0d0-afac-11de-8a39-0800200c9a66");

 

(2)发现AcceptThread中BluetoothServerSocket.accept()方法出现异常,但没有弄明白异常的根源在哪里。实现蓝牙透传功能不需要一个Server程序在等待,所以就不用创建Server线程,就不会执行到accept()方法。

// Start the thread to listen on a BluetoothServerSocket
/*if (mAcceptThread == null) {
    mAcceptThread = new AcceptThread();
    mAcceptThread.start();
}*/
 

(3)发现HC-6蓝牙模块有一根线和PCB板没有连上,导致手机程序无法读到数据。

 

(4)往蓝牙模块发送请求APDU时,需要将ASCII字符串转换为十六进制的字节数组。

// ASCII字符串转换为十六进制字节数组
private byte[] convert2HexArray(String apdu)
{            
    int len = apdu.length() / 2;
    char[] chars = apdu.toCharArray();
    String[] hexes = new String[len];
    byte[] bytes = new byte[len];
    for (int i = 0, j = 0; j < len; i = i + 2, j++)
    {
        hexes[j] = "" + chars[i] + chars[i + 1];
        bytes[j] = (byte)Integer.parseInt(hexes[j],16);
    }
    return bytes;
}

// 在程序中调用conver2HexArray方法
byte[] send = this.convert2HexArray(message); 
mChatService.write(send);

 

(5)接收来自蓝牙模块的响应APDU时,需要将十六进制的字节数组转换为ASCII字符串,然后才可以显示。

// 十六进制字节数组转换为ASCII字符串,指定元素个数
public String bytes2HexString(byte[] b, int count) {
    String ret = "";
    for (int i = 0; i < count; i++) {
        String hex = Integer.toHexString(b[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        ret += hex.toUpperCase();
    }
    return ret;
}

// 十六进制字节数组转换为ASCII字符串
public String bytes2HexString(byte[] b) {
    String ret = "";
    for (int i = 0; i < b.length; i++) {
        String hex = Integer.toHexString(b[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        ret += hex.toUpperCase();
    }
    return ret;
}

// 在程序中调用bytes2HexString方法
byte[] readBuf = (byte[]) msg.obj;
String readMsg = bytes2HexString(readBuf,msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMsg);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值