手机蓝牙连接相关问题

1.蓝牙连接错误

java.io.IOException: read failed, socket might closed or timeout, read ret: -1
解决方法:
在连接异常中,使用新的方式实例化
private BluetoothDevice device = null;
private static BluetoothSocket bluetoothSocket = null;
private static OutputStream outputStream = null;
private static final UUID uuid = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");//服务的唯一标识 android的API上面说明的,用于普通蓝牙适配器和android手机蓝牙模块连接的
private boolean isConnection = false;

 /**
 * 连接蓝牙设备
 */
public boolean connect() {
    if (!this.isConnection) {
        try {
            bluetoothSocket = this.device.createRfcommSocketToServiceRecord(uuid);
            bluetoothSocket.connect();
            outputStream = bluetoothSocket.getOutputStream();
            this.isConnection = true;
            if (this.bluetoothAdapter.isDiscovering()) {
                System.out.println("关闭适配器!");
                this.bluetoothAdapter.isDiscovering();
            }
        } catch (Exception e) {
            Log.i("wyy", "connect: e = " + e.getMessage());
            e.printStackTrace();
            //以下为新的创建方式
            try {
                Log.e("wyy", "trying fallback...");

                bluetoothSocket = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
                bluetoothSocket.connect();
                outputStream = bluetoothSocket.getOutputStream();
                this.isConnection = true;

                Log.e("wyy", "Connected");
            } catch (Exception e2) {
                Log.e("wyy", "Couldn't establish Bluetooth connection!");
                return false;
            }
        }
        Toast.makeText(this.context, this.device.getName() + "打印机打印成功!",
                Toast.LENGTH_SHORT).show();
        return true;
    } else {
        return true;
    }
}

2.蓝牙连接的断开问题
蓝牙打印,每次发送命令的时候,必须确保之前的连接断开,重新连接才能够发送指令成功。
开始的思路:每次发送完打印指令都会断开连接,这样就会存在问题,命令没有执行完,连接就断开了,导致小票未完全打印出来。
后来更换思路:每次发送完打印指令不去断开连接,每次重新连接之前去判断上次的连接是否断开,如没断开,则先断开连接再重新连接,避免了上述方案的问题。
PS:也可参照socket缓存设置,待缓存数据传递完成之后,再把连接关闭。因对其原理不太清楚,还未找到相关的解决方案。

猜你喜欢

转载自blog.csdn.net/sindyue/article/details/74668373
今日推荐