安卓蓝牙USB连接热敏打印机一

来源:互联网 发布:java抽奖概率算法控制 编辑:程序博客网 时间:2024/09/21 09:24


安卓蓝牙连接打印机

       首先,你的热敏打印机必须支持蓝牙,我选择的是芯华xp-58iih这款。此款支持蓝牙连接和USB连接。

       由于我不想每次打印的时候去搜索蓝牙设备,所以我提前使用平板配备上了这款蓝牙打印机。

      

      这样,我就可以在程序中直接找到这个蓝牙设备,并打印数据。

      第一,实例化一个蓝牙适配器

     BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      第二,找到蓝牙设备地址

      Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
      for (BluetoothDevice bluetoothDevice : bondedDevices) { deviceAddress = bluetoothDevice.getAddress(); }

      第三,获取设备,连接,获取流

      device = bluetoothAdapter.getRemoteDevice(deviceAddress);

      bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
      bluetoothSocket.connect();
      outputStream = bluetoothSocket.getOutputStream();

     第四,传入数据,进行打印

     byte[] printData = data.getBytes("gbk");
     outputStream.write(printData, 0, printData.length);
     outputStream.flush();

     完毕后,记得关闭

     bluetoothSocket.close();

     outputStream.close();

     测试结果如下:

    

 当然,我们还需要在AndroidManifest.xml中分配权限:

     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  

废话不多说,详细的代码请下载:http://download.csdn.net/detail/konkon2012/9383696 


0 0
原创粉丝点击