1

我正在尝试连接到 USB 打印机并从中打印数据。我正在使用下面的代码来执行此操作,以下事情正在发生。

  • 我从手机启动应用程序 - 应用程序打开并显示带有“打印”按钮的屏幕。

  • 当我通过 OTG 电缆连接打印机 USB 时,弹出权限对话框,我在其中选择允许权限。

  • 现在我按下“打印”按钮,我看到了放在代码中的祝酒词

    1>“设备数量:1”

    2>“设备已连接”

    3>“printdata.getBytes().length ====>”

  • 打印机显示“正在接收数据”,但之后它什么也不做。一切正常,但问题是没有打印

    public class USBAdapter {
    
    private UsbManager mUsbManager;
    private UsbDevice mDevice;
    UsbDevice printer = null;
    private PendingIntent mPermissionIntent;
    UsbDeviceConnection connection;
    String TAG = "USB";
    private static final String ACTION_USB_PERMISSION =  "com.android_usb_printer.USB_PERMISSION";
    
    
    public USBAdapter() {
    }
    
    public void createConn(Context context) {
        mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        if (deviceList.size() <= 0) {
            Log.i("Info", "No device found");
            Toast.makeText(context, "No device found", Toast.LENGTH_SHORT).show();
        } else {
            Log.i("Info", "Number of device : " + deviceList.size());
            Toast.makeText(context, "Number of device : " + deviceList.size(), Toast.LENGTH_SHORT).show();
    
        }
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        while (deviceIterator.hasNext()) {
            mDevice = deviceIterator.next();
            Log.i("info", "Vendor id : " + mDevice.getVendorId());
            Log.i("info", "Product id : " + mDevice.getProductId());
            Log.i("info", "Device  name : " + mDevice.getDeviceName());
            Log.i("info", "Device class : " + mDevice.getClass().getName());
            Log.i("info", "Device protocol: " + mDevice.getDeviceProtocol());
            Log.i("info", "Device subclass : " + mDevice.getDeviceSubclass());
    
        }
        /*final String ACTION_USB_PERMISSION = "com.android_usb_printer.USB_PERMISSION";
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        context.registerReceiver(mUsbReceiver, filter);*/
    }
    
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    
        public void onReceive(Context context, Intent intent) {
            System.out.println("<=======Onreceived=======>");
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    mDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    Toast.makeText(context, "mDevice ====>"+mDevice, Toast.LENGTH_SHORT).show();
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (mDevice != null) {
                            //call method to set up device communication
                        }
                    } else {
                        Log.d(TAG, "permission denied for device " + mDevice);
                    }
                }
            }
        }
    };
    
    @SuppressLint("NewApi")
    public void printMessage(final Context context, String msg) {
        // TODO Auto-generated method stub
        final String printdata = msg;
        final UsbEndpoint mEndpointBulkOut;
        if (mUsbManager.hasPermission(mDevice)) {
            UsbInterface intf ;
            for(int i = 0; i < mDevice.getInterfaceCount(); i++){
                intf = mDevice.getInterface(i);
                if(intf.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER){
                    printer = mDevice;
    
                    UsbEndpoint ep = intf.getEndpoint(i);
                    int b;
                    if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                        if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                            mEndpointBulkOut = ep;
                            connection = mUsbManager.openDevice(printer);
                            if (connection != null) {
                                Log.e("Connection:", " connected");
                                Toast.makeText(context, "Device connected", Toast.LENGTH_SHORT).show();
                            }
    
                            Toast.makeText(context, "printdata.getBytes().length ====>"+printdata.getBytes().length, Toast.LENGTH_SHORT).show();
    
                            boolean forceClaim = true;
                            connection.claimInterface(intf, forceClaim);
                            //Integer res = connection.bulkTransfer(mEndpointBulkOut, printdata.getBytes(), printdata.getBytes().length, 10000);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    Log.i("Thread:", "in run thread");
                                    byte[] bytes = printdata.getBytes();
                                    int b = connection.bulkTransfer(mEndpointBulkOut, bytes, bytes.length, 100000);
                                    Log.i("Return Status", "b-->" + b);
                                }
                            }).start();
                            connection.releaseInterface(intf);
                            break;
                        }
                    }
                }
            }
        } else {
            mUsbManager.requestPermission(mDevice, mPermissionIntent);
            Toast.makeText(context, "Device have no permission", Toast.LENGTH_SHORT).show();
        }
    }
    
    @SuppressLint("NewApi")
    public void closeConnection(Context context) {
        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
    
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        Toast.makeText(context, "Device closed", Toast.LENGTH_SHORT).show();
                        connection.close();
                    }
                }
            }
        };
    }
    }
    

printMessage()正在从我出错的MainActivityonclick()点中的打印按钮调用。谢谢。

4

0 回答 0