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); 
  • 相关阅读:
    非阻塞式线程安全列表-ConcurrentLinkedDeque
    计数器
    Linux 查看服务器内存使用情况
    Oracle to_date, to_timestamp
    Hibernate session.flush() 使用
    阿里规约认证(题库附答案)
    多态性
    Java数据类型
    String类特点分析
    数组的定义
  • 原文地址:https://www.cnblogs.com/jiayonghua/p/10401289.html
Copyright © 2011-2022 走看看