无法将数据从Android手机打印到Usb打印机

时间:2016-03-10 13:46:17

标签: android multithreading android-usb

我正在尝试连接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()正在 MainActivity 点的onclick()打印按钮中调用,我错了。 感谢。

0 个答案:

没有答案