手机蓝牙连接相关问题

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缓存设置,待缓存数据传递完成之后,再把连接关闭。因对其原理不太清楚,还未找到相关的解决方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值