zoukankan      html  css  js  c++  java
  • Android 小票打印USB

    第一步USB通信:

    Usb设备有两种,Host与Accessory 简单来说是主模式与从模式,主模式则android设备给外设供电,反之,外设给android设备充电,对于小票打印,使用的是Host模式

    用到以下几个类:

    1.UsbManager: 这个类用来获取USB设备-UsbDevice

    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    // 获取设备
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

    UsbInterface & UsbEndpoint : 代表UsbDevice有哪些功能

    UsbInterface intf = device.getInterface(0);
    // 官方文档上边是这样写的,直接获取第一个,但往往不一定只连接一个设备,就要求我们找到自己想要的那个,一般的做法是
    int count = device.getInterfaceCount();
    for (int i = 0;i < count; i++) {
          UsbInterface intf = device.getInterface(i);
          // 之后我们会根据 intf的 getInterfaceClass 判断是哪种类型的Usb设备,
         // 并且结合 device.getVectorID() 或者厂家ID进行过滤,比如 UsbConstants.USB_CLASS_PRINTER
        if (device.getVectorID() == '打印机的生产商ID' && 
             intf.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER) {
            // 这个device就是你要找的UsbDevice,此时还需要进行权限判断
           if (usbManager.hasPermission(device) == false) { // 没有权限
                 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.android.example.USB_PERMISSION"), 0);
                 IntentFilter filter = new IntentFilter("com.android.example.USB_PERMISSION");
                 registerReceiver(mUsbReceiver, filter);     
                 return;
           }
        }
    }

    建立连接:

    UsbDeviceConnection connection = mUsbManager.openDevice(device);
    connection.claimInterface(intf, forceClaim);

    开始写数据:

    //do in another thread
    connection.bulkTransfer(outEndpoint, bytes, bytes.length, TIMEOUT); 

    开始读数据:

    //do in another thread
    connection.bulkTransfer(inEndpoint, bytes, bytes.length, TIMEOUT); 

    初始化打印机:

    byte[] bytes = new bytes[]{(byte) 27, (byte) 64};
    connection.bulkTransfer(outEndpoint, bytes, bytes.length, TIMEOUT); 

    输出要打印的格式:

    byte[] bytes = "你要打印的文字".getBytes("gbk");
    connection.bulkTransfer(outEndpoint, bytes, bytes.length, TIMEOUT); 

    输出换行:

    byte[] bytes = new bytes[]{(byte) 10};
    connection.bulkTransfer(outEndpoint, bytes, bytes.length, TIMEOUT); 
  • 相关阅读:
    打开模拟器genymotion 的设置 查询设置的包名
    python 地板除 向下取整 取比目标结果小的的最大整数
    python 复数
    python 0.1+0.2 不等于0.3 的处理办法
    python 利用随机数的种子,复现随机数
    小程序 单独页面的js文件里设置 数据绑定
    问题集
    2020软件工程个人作业06——软件工程实践总结作业
    2020软件工程作业05
    2020软件工程作业04
  • 原文地址:https://www.cnblogs.com/jiayonghua/p/10401289.html
Copyright © 2011-2022 走看看