Android接入热敏打印机

首先是解析类 PrintUser

public class PrintUser implements Serializable { 

    /** * pharmacy : 药房 * orderTime : 下单时间 * orderNumber : 订单号 * agentName : 终端名称 * agentCode : 终端编号 * purchaseType : 购药类型 * drug : [{"productName":"品名","specification":"规格","lotNumber":"批号","factory":"厂家","unitPrice":"单价","quantity":"数量","amount":"金额"}] * paymentTypes : 支付类型 * total : 合计 * payable : 应付 * actualCollection : 实收 * change : 找零 * receipt : 收据号 * printTime : 打印时间 */

    private String pharmacy;
    private String orderTime;
    private String orderNumber;
    private String agentName;
    private String agentCode;
    private String purchaseType;
    private String paymentTypes;
    private String total;
    private String payable;
    private String actualCollection;
    private String change;
    private String receipt;
    private String printTime;
    private List<DrugBean> drug;

    public PrintUser(String pharmacy, String orderTime, String orderNumber, String agentName, String agentCode, String purchaseType, String paymentTypes, String total, String payable, String actualCollection, String change, String receipt, String printTime, List<DrugBean> drug) { 
        this.pharmacy = pharmacy;
        this.orderTime = orderTime;
        this.orderNumber = orderNumber;
        this.agentName = agentName;
        this.agentCode = agentCode;
        this.purchaseType = purchaseType;
        this.paymentTypes = paymentTypes;
        this.total = total;
        this.payable = payable;
        this.actualCollection = actualCollection;
        this.change = change;
        this.receipt = receipt;
        this.printTime = printTime;
        this.drug = drug;
    }

    public String getPharmacy() { 
        return pharmacy;
    }

    public void setPharmacy(String pharmacy) { 
        this.pharmacy = pharmacy;
    }

    public String getOrderTime() { 
        return orderTime;
    }

    public void setOrderTime(String orderTime) { 
        this.orderTime = orderTime;
    }

    public String getOrderNumber() { 
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) { 
        this.orderNumber = orderNumber;
    }

    public String getAgentName() { 
        return agentName;
    }

    public void setAgentName(String agentName) { 
        this.agentName = agentName;
    }

    public String getAgentCode() { 
        return agentCode;
    }

    public void setAgentCode(String agentCode) { 
        this.agentCode = agentCode;
    }

    public String getPurchaseType() { 
        return purchaseType;
    }

    public void setPurchaseType(String purchaseType) { 
        this.purchaseType = purchaseType;
    }

    public String getPaymentTypes() { 
        return paymentTypes;
    }

    public void setPaymentTypes(String paymentTypes) { 
        this.paymentTypes = paymentTypes;
    }

    public String getTotal() { 
        return total;
    }

    public void setTotal(String total) { 
        this.total = total;
    }

    public String getPayable() { 
        return payable;
    }

    public void setPayable(String payable) { 
        this.payable = payable;
    }

    public String getActualCollection() { 
        return actualCollection;
    }

    public void setActualCollection(String actualCollection) { 
        this.actualCollection = actualCollection;
    }

    public String getChange() { 
        return change;
    }

    public void setChange(String change) { 
        this.change = change;
    }

    public String getReceipt() { 
        return receipt;
    }

    public void setReceipt(String receipt) { 
        this.receipt = receipt;
    }

    public String getPrintTime() { 
        return printTime;
    }

    public void setPrintTime(String printTime) { 
        this.printTime = printTime;
    }

    public List<DrugBean> getDrug() { 
        return drug;
    }

    public void setDrug(List<DrugBean> drug) { 
        this.drug = drug;
    }

    public static class DrugBean implements Serializable { 
        /** * productName : 品名 * specification : 规格 * lotNumber : 批号 * factory : 厂家 * unitPrice : 单价 * quantity : 数量 * amount : 金额 */

        private String productName;
        private String specification;
        private String lotNumber;
        private String factory;
        private String unitPrice;
        private String quantity;
        private String amount;

        public DrugBean(String productName, String specification, String lotNumber, String factory, String unitPrice, String quantity, String amount) { 
            this.productName = productName;
            this.specification = specification;
            this.lotNumber = lotNumber;
            this.factory = factory;
            this.unitPrice = unitPrice;
            this.quantity = quantity;
            this.amount = amount;
        }

        public String getProductName() { 
            return productName;
        }

        public void setProductName(String productName) { 
            this.productName = productName;
        }

        public String getSpecification() { 
            return specification;
        }

        public void setSpecification(String specification) { 
            this.specification = specification;
        }

        public String getLotNumber() { 
            return lotNumber;
        }

        public void setLotNumber(String lotNumber) { 
            this.lotNumber = lotNumber;
        }

        public String getFactory() { 
            return factory;
        }

        public void setFactory(String factory) { 
            this.factory = factory;
        }

        public String getUnitPrice() { 
            return unitPrice;
        }

        public void setUnitPrice(String unitPrice) { 
            this.unitPrice = unitPrice;
        }

        public String getQuantity() { 
            return quantity;
        }

        public void setQuantity(String quantity) { 
            this.quantity = quantity;
        }

        public String getAmount() { 
            return amount;
        }

        public void setAmount(String amount) { 
            this.amount = amount;
        }

        @Override
        public String toString() { 
            return "DrugBean{" +
                    "productName='" + productName + '\'' +
                    ", specification='" + specification + '\'' +
                    ", lotNumber='" + lotNumber + '\'' +
                    ", factory='" + factory + '\'' +
                    ", unitPrice='" + unitPrice + '\'' +
                    ", quantity='" + quantity + '\'' +
                    ", amount='" + amount + '\'' +
                    '}';
        }
    }

    @Override
    public String toString() { 
        return "PrintUser{" +
                "pharmacy='" + pharmacy + '\'' +
                ", orderTime='" + orderTime + '\'' +
                ", orderNumber='" + orderNumber + '\'' +
                ", agentName='" + agentName + '\'' +
                ", agentCode='" + agentCode + '\'' +
                ", purchaseType='" + purchaseType + '\'' +
                ", paymentTypes='" + paymentTypes + '\'' +
                ", total='" + total + '\'' +
                ", payable='" + payable + '\'' +
                ", actualCollection='" + actualCollection + '\'' +
                ", change='" + change + '\'' +
                ", receipt='" + receipt + '\'' +
                ", printTime='" + printTime + '\'' +
                ", drug=" + drug +
                '}';
    }
}

然后是打印的类printSeviec

public class printServiec extends Service { 
    UsbDriver mUsbDriver;
    private final String TAG = "printServiec";
    private UsbManager mUsbManager;
    private UsbDevice m_Device;
    UsbDevice mUsbDev1;        //打印机1
    UsbDevice mUsbDev2;        //打印机2
    private int cutter = 1;       // 默认0, 0 全切、1 半切
    private String divider = "-------------------------------";
    private final static int PID11 = 8211;
    private final static int PID13 = 8213;
    private final static int PID15 = 8215;
    private final static int VENDORID = 1305;
    private static final String ACTION_USB_PERMISSION = "com.usb.sample.USB_PERMISSION";


    @Override
    public void onCreate() { 
        getUsbDriverService();
        super.onCreate();
    }

    public static void start(Context context, PrintUser printUser) { 
        Intent intent = new Intent(context, printServiec.class);
        intent.putExtra("printUser", printUser);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
        String ht1, ht2, ht3 = "";
        if (intent == null) return START_NOT_STICKY;
        if (printConnStatus()) { 
            PrintUser printUser = (PrintUser) intent.getSerializableExtra("printUser");
            Log.e(TAG, printUser.toString());
            int status = getPrinterStatus2(mUsbDev1);
            if (status != 3) { 
                try { 
                    mUsbDriver.write(PrintCmd.SetReadZKmode(0));
                    mUsbDriver.write(PrintCmd.SetBold(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetSizetext(1, 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getPharmacy() + "\n\n", 0), mUsbDev1);
                    // 小票主要内容
                    mUsbDriver.write(PrintCmd.SetLinespace(40));
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetSizetext(0, 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(divider + "\n下单时间:" + printUser.getOrderTime() + "\n"
                            + "订单号:" + printUser.getOrderNumber() + "\n"
                            + "终端名称:" + printUser.getAgentName() + "\n"
                            + "终端编号:" + printUser.getAgentCode() + "\n"
                            + "购药类型:" + printUser.getPurchaseType() + "\n"
                            + divider, 0), mUsbDev1);
                    String Col1 = SystemUtil.intToHexString(Integer.valueOf(15), 1) + " ";// 转换第1列
                    String Col2 = SystemUtil.intToHexString(Integer.valueOf(25), 1) + " ";// 转换第2列
                    ht1 = SystemUtil.stringTo16Hex("品名/规格");
                    ht2 = SystemUtil.stringTo16Hex("批号");
                    ht3 = SystemUtil.stringTo16Hex("厂家");
                    String etstring = Col1 + Col2 + "00 " + ht1 + "09 " +
                            ht2 + "09 " + ht3 + "09 0A 0A 0A";
                    byte[] seat = SystemUtil.hexStr2Bytesnoenter(etstring);
                    mUsbDriver.write(PrintCmd.SetHTseat(seat, seat.length), seat.length, mUsbDev1);
// mUsbDriver.write(PrintCmd.PrintString("\n", 0), mUsbDev1);
                    ht1 = SystemUtil.stringTo16Hex("单价");
                    ht2 = SystemUtil.stringTo16Hex("数量");
                    ht3 = SystemUtil.stringTo16Hex("金额");
                    etstring = Col1 + Col2 + "00 " + ht1 + "09 " +
                            ht2 + "09 " + ht3 + "09 0A 0A";
                    seat = SystemUtil.hexStr2Bytesnoenter(etstring);
                    mUsbDriver.write(PrintCmd.SetHTseat(seat, seat.length), seat.length, mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("\n" + divider, 0), mUsbDev1);
                    for (int i = 0; i < printUser.getDrug().size(); i++) { 
                        if (i > 0) { 
                            mUsbDriver.write(PrintCmd.PrintString("\n", 0), mUsbDev1);
                        }
                        ht1 = printUser.getDrug().get(i).getProductName() + "/" + printUser.getDrug().get(i).getSpecification();
                        if (printUser.getDrug().get(i).getLotNumber() != null && !printUser.getDrug().get(i).getLotNumber().equals("")) { 
                            ht2 = printUser.getDrug().get(i).getLotNumber();
                        }
                        if (printUser.getDrug().get(i).getFactory() != null && !printUser.getDrug().get(i).getFactory().equals("")) { 
                            ht3 = printUser.getDrug().get(i).getFactory();
                        }
                        mUsbDriver.write(PrintCmd.PrintString(ht1, 0), mUsbDev1);
                        if (printUser.getDrug().get(i).getLotNumber() != null && !printUser.getDrug().get(i).getLotNumber().equals("")) { 
                            mUsbDriver.write(PrintCmd.PrintString(ht2, 0), mUsbDev1);
                        }
                        if (printUser.getDrug().get(i).getFactory() != null && !printUser.getDrug().get(i).getFactory().equals("")) { 
                            mUsbDriver.write(PrintCmd.PrintString(ht3, 0), mUsbDev1);
                        }
                        ht1 = SystemUtil.stringTo16Hex(printUser.getDrug().get(i).getUnitPrice());
                        ht2 = SystemUtil.stringTo16Hex(printUser.getDrug().get(i).getQuantity());
                        ht3 = SystemUtil.stringTo16Hex(printUser.getDrug().get(i).getAmount());
                        etstring = Col1 + Col2 + "00 " + ht1 + "09 " +
                                ht2 + "09 " + ht3 + "09 0A 0A";
                        seat = SystemUtil.hexStr2Bytesnoenter(etstring);
                        mUsbDriver.write(PrintCmd.SetHTseat(seat, seat.length),
                                seat.length, mUsbDev1);
                    }
                    mUsbDriver.write(PrintCmd.PrintString("\n" + divider, 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetSizetext(1, 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("合计:", 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(2), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getTotal(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetSizetext(0, 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getPaymentTypes(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(divider, 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("应付:", 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(2), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getPayable(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("实收:", 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(2), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getActualCollection(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("找零:", 1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(2), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(printUser.getChange(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString(divider, 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
// mUsbDriver.write(PrintCmd.PrintString("收据号:" + printUser.getReceipt(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetLinespace(80));
                    mUsbDriver.write(PrintCmd.PrintString("打印时间:" + printUser.getPrintTime(), 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(1), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetLinespace(40));
                    mUsbDriver.write(PrintCmd.PrintString("谢谢惠顾" , 0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.SetAlignment(0), mUsbDev1);
                    mUsbDriver.write(PrintCmd.PrintString("为维护健康,请遵医嘱或按说明书提示使用,除药品质量问题外,药品一经售出,不予退换\n" , 0), mUsbDev1);
                    setFeedCut(cutter, mUsbDev1);
                    postMsg("print", "true");
                } catch (Exception e) { 
                    setFeedCut(cutter, mUsbDev1);
                    postMsg("print", "false");
                    Log.i(TAG,"打印错误:" + e.getMessage());
                    LogHandler.writeFile(TAG, "打印错误:" + e.getMessage());
                }
            } else { 
                postMsg("print", "false");
                Log.i(TAG,"打印机状态值:" + String.valueOf(status));
                LogHandler.writeFile(TAG, "打印机状态值:" + String.valueOf(status));
            }
        } else { 
            postMsg("print", "false");
            Log.i(TAG,"打印机驱动失败");
            LogHandler.writeFile(TAG, "打印机驱动失败");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) { 
        throw new UnsupportedOperationException("Not yet implemented");
    }

    // Get UsbDriver(UsbManager) service
    private boolean printConnStatus() { 

        boolean blnRtn = false;
        try { 
            if (!mUsbDriver.isConnected()) { 
// UsbManager m_UsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                // USB线已经连接
                for (UsbDevice device : mUsbManager.getDeviceList().values()) { 
                    Log.i("device.getProductId()", String.valueOf(device.getProductId()));
                    Log.i("device.getVendorId()", String.valueOf(device.getVendorId()));
                    if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) { 
                        if (!mUsbManager.hasPermission(device)) { 
                            break;
                        }
                        blnRtn = mUsbDriver.usbAttached(device);
                        if (blnRtn == false) { 
                            break;
                        }
                        blnRtn = mUsbDriver.openUsbDevice(device);
                        // 打开设备
                        if (blnRtn) { 
                            if (device.getProductId() == PID11) { 
                                mUsbDev1 = device;
                            } else { 
                                mUsbDev2 = device;
                            }
                            setClean();// 清理缓存,初始化
                            Log.e(TAG, "驱动成功");
                            break;
                        } else { 
                            Log.e(TAG, "驱动失败");
                            break;
                        }
                    }
                }
            } else { 
                blnRtn = true;
            }
        } catch (Exception e) { 
            Log.e("printServiec", "ERROE:" + e.getMessage());
        }
        return blnRtn;
    }

    // 常规设置
    private void setClean() { 
        mUsbDriver.write(PrintCmd.SetClean());// 清除缓存,初始化
    }

    /* * BroadcastReceiver when insert/remove the device USB plug into/from a USB port * 创建一个广播接收器接收USB插拔信息:当插入USB插头插到一个USB端口,或从一个USB端口,移除装置的USB插头 */
    BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { 
        public void onReceive(Context context, Intent intent) { 
            String action = intent.getAction();
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { 
                if (mUsbDriver.usbAttached(intent)) { 
                    UsbDevice device = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) { 
                        if (mUsbDriver.openUsbDevice(device)) { 
                            if (device.getProductId() == PID11)
                                mUsbDev1 = device;
                            else
                                mUsbDev2 = device;
                        }
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { 
                UsbDevice device = (UsbDevice) intent
                        .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                        || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                        || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) { 
                    mUsbDriver.closeUsbDevice(device);
                    if (device.getProductId() == PID11)
                        mUsbDev1 = null;
                    else
                        mUsbDev2 = null;
                }
            } else if (ACTION_USB_PERMISSION.equals(action)) { 
                synchronized (this) { 
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { 
                        if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) { 
                            if (mUsbDriver.openUsbDevice(device)) { 
                                if (device.getProductId() == PID11)
                                    mUsbDev1 = device;
                                else
                                    mUsbDev2 = device;
                            }
                        }
                    } else { 
                        Log.e(TAG, "permission denied for device");
                        //Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    private void getUsbDriverService() { 
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mUsbDriver = new UsbDriver(mUsbManager, this);
        PendingIntent permissionIntent1 = PendingIntent.getBroadcast(printServiec.this, 0,
                new Intent(ACTION_USB_PERMISSION), 0);
        mUsbDriver.setPermissionIntent(permissionIntent1);

        // Broadcast listen for new devices
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        printServiec.this.registerReceiver(mUsbReceiver, filter);
    }

    // 检测打印机状态
    private int getPrinterStatus2(UsbDevice usbDev) { 
        int iRet = -1;

        byte[] bRead5 = new byte[1];
        byte[] bWrite5 = sendCommand();
        if (mUsbDriver.read(bRead5, bWrite5, usbDev) > 0) { 
            Log.e(TAG, "返回值:" + String.valueOf(bRead5[0]));
            iRet = checkStatus(bRead5[0]);
        }
        if (iRet == 0 || iRet > 0)
            return iRet;
        return iRet;
    }

    // 发送打印完成指令 1D 72 01
    private byte[] sendCommand() { 
        byte[] b_send = new byte[3];
        int iIndex = 0;
        b_send[(iIndex++)] = 0x1D;
        b_send[(iIndex++)] = 0x72;
        b_send[(iIndex++)] = 0x01;
        return b_send;
    }

    // 解析
    public static int checkStatus(byte bRecv) { 
        if ((bRecv & 0x00) == 0x00)
            return 0;  // 打印纸充足
        if ((bRecv & 0x03) == 0x03)
            return 1;  // 打印纸将尽
        if ((bRecv & 0x60) != 0x60)
            return 2;  // 打印机非空闲状态
        return 3;      // 空闲状态
    }

    // 走纸换行、切纸、清理缓存
    private void setFeedCut(int iMode, UsbDevice usbDev) { 
        mUsbDriver.write(PrintCmd.PrintFeedline(5), usbDev);      // 走纸换行
        mUsbDriver.write(PrintCmd.PrintCutpaper(iMode), usbDev);  // 切纸类型
    }

    /** * @param resultCode 不能为空 * @param resultInfo default is ""; */
    private void postMsg(String resultCode, String resultInfo) { 
        /*Log.d(TAG, "postMsg: " + String.format("%s,%s,%s" , "bellows" , resultCode , TextUtils.isEmpty(resultInfo) ? "null" : resultInfo));*/
        ProcessReceiver.sendParams(printServiec.this, String.format("%s,%s,%s"
                , ProcessReceiver.CMD_BELLOWS
                , resultCode
                , TextUtils.isEmpty(resultInfo) ? "null" : resultInfo));
    }
}

调用:

String print = "{\"pharmacy\":\"微信支付宝\",\"orderTime\":\"2020/11/13 16:52:44\",\"orderNumber\":\"1327172533161558016\",\"agentName\":\"测试机\",\"agentCode\":\"hwj0006\",\"purchaseType\":\"终端购药\",\"drug\":[{\"productName\":\"拜敏万全 氯雷他定片\",\"specification\":\"10mg*6s\",\"factory\":\"\",\"lotNumber\":\"\",\"quantity\":1,\"amount\":0.01,\"unitPrice\":0.01}],\"paymentTypes\":\"在线支付\",\"total\":\"0.01\",\"payable\":\"0.01\",\"actualCollection\":0.01,\"change\":0,\"printTime\":\"2020/11/13 16:53:07\"}";
                Gson gson = new Gson();
                PrintUser printUser = gson.fromJson(print,PrintUser.class);
                printServiec.start(context,printUser);

以及获取USB权限:

/** * 获得 usb 权限[文件] */
    private void openUsbDevice(){ 
        //before open usb device
        //should try to get usb permission
        tryGetUsbPermission();
    }
    UsbManager mUsbManager;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    private void tryGetUsbPermission(){ 
        mUsbManager = (UsbManager) App.getContext().getSystemService(Context.USB_SERVICE);

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        App.getContext().registerReceiver(mUsbPermissionActionReceiver, filter);

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(App.getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);

        //here do emulation to ask all connected usb device for permission
        for (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) { 
            //add some conditional check if necessary
            //if(isWeCaredUsbDevice(usbDevice)){ 
            if(mUsbManager.hasPermission(usbDevice)){ 
                //if has already got permission, just goto connect it
                //that means: user has choose yes for your previously popup window asking for grant perssion for this usb device
                //and also choose option: not ask again
                afterGetUsbPermission(usbDevice);
            }else{ 
                //this line will let android popup window, ask user whether to allow this app to have permission to operate this usb device
                mUsbManager.requestPermission(usbDevice, mPermissionIntent);
            }
            //}
        }
    }


    private void afterGetUsbPermission(UsbDevice usbDevice){ 
        //call method to set up device communication
        //Toast.makeText(this, String.valueOf("Got permission for usb device: " + usbDevice), Toast.LENGTH_LONG).show();
        //Toast.makeText(this, String.valueOf("Found USB device: VID=" + usbDevice.getVendorId() + " PID=" + usbDevice.getProductId()), Toast.LENGTH_LONG).show();

        doYourOpenUsbDevice(usbDevice);
    }

    private void doYourOpenUsbDevice(UsbDevice usbDevice){ 
        //now follow line will NOT show: User has not given permission to device UsbDevice
        UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);
        //add your operation code here
    }

    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() { 
        public void onReceive(Context context, Intent intent) { 
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) { 
                synchronized (this) { 
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { 
                        //user choose YES for your previously popup window asking for grant perssion for this usb device
                        if(null != usbDevice){ 
                            afterGetUsbPermission(usbDevice);
                        }
                    }
                    else { 
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                        Toast.makeText(context, String.valueOf("Permission denied for device" + usbDevice), Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

如果打印机的和我所使用的不一样,那么需要先获取到设备的VID和PID,再把printSeviec类中的换一下就行

    原文作者:zhaochengfang
    原文地址: https://blog.csdn.net/zhaochengfang/article/details/109687418
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞