如何使用USB OTG在Canon 2900B上打印?

时间:2019-06-01 08:22:20

标签: java android

尝试这个。

public class MainActivity extends Activity {
    PendingIntent mPermissionIntent;
    Button btnCheck;
    TextView textInfo;
    UsbDevice device;
    UsbManager manager;
    private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCheck = (Button) findViewById(R.id.check);
        textInfo = (TextView) findViewById(R.id.info);
        btnCheck.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                textInfo.setText("");
                checkInfo();
            }
        });

    }


    public void startPrinting(final UsbDevice printerDevice) {
        new Handler().post(new Runnable() {
            UsbDeviceConnection conn;
            UsbInterface usbInterface;

            @Override
            public void run() {
                try {
                    Log.e("Info", "Bulk transfer started");
                    usbInterface = printerDevice.getInterface(0);
                    UsbEndpoint endPoint = usbInterface.getEndpoint(0);
                    conn = manager.openDevice(device);
                    conn.claimInterface(usbInterface, true);
                    String myStringData = "\nThis \nis \nmy \nsample \ntext";
                    byte[] array = myStringData.getBytes();
                    ByteBuffer output_buffer = ByteBuffer
                            .allocate(array.length);
                    UsbRequest request = new UsbRequest();
                    request.initialize(conn, endPoint);
                    request.queue(output_buffer, array.length);
                    if (conn.requestWait() == request) {
                        Log.i("Info", output_buffer.getChar(0) + "");
                        Message m = new Message();
                        m.obj = output_buffer.array();
                        // handler.sendMessage(m);
                        output_buffer.clear();
                    } else {
                        Log.e("Info", "No request recieved");
                    }
                    // int transfered = conn.bulkTransfer(endPoint,
                    // myStringData.getBytes(),
                    // myStringData.getBytes().length, 5000);
                    // Log.i("Info", "Amount of data transferred : " +
                    // transfered);

                } catch (Exception e) {
                    Log.e("Exception", "Unable to transfer bulk data");
                    e.printStackTrace();
                } finally {
                    try {
                        conn.releaseInterface(usbInterface);
                        Log.e("Info", "Interface released");
                        conn.close();
                        Log.e("Info", "Usb connection closed");
                        unregisterReceiver(mUsbReceiver);
                        Log.e("Info", "Brodcast reciever unregistered");
                    } catch (Exception e) {
                        Log.e("Exception",
                                "Unable to release resources because : "
                                        + e.getMessage());
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    private void checkInfo() {
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        /*
         * this block required if you need to communicate to USB devices it's
         * take permission to device
         * if you want than you can set this to which device you want to communicate   
         */
        // ------------------------------------------------------------------
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filter);
        // -------------------------------------------------------------------
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        String i = "";
        while (deviceIterator.hasNext()) {
            device = deviceIterator.next();
            manager.requestPermission(device, mPermissionIntent);
            i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
                    + "DeviceName: " + device.getDeviceName() + "\n"
                    + "DeviceClass: " + device.getDeviceClass() + " - "
                    + "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
                    + "VendorID: " + device.getVendorId() + "\n"
                    + "ProductID: " + device.getProductId() + "\n";
        }

        textInfo.setText(i);
        if(!(i.equalsIgnoreCase("")))
        {
            startPrinting(device);
        }

    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            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 != null) {
                            // call method to set up device communication
                        }
                    } else {
                        Log.d("ERROR", "permission denied for device " + device);
                    }
                }
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();

            unregisterReceiver(mUsbReceiver);

    }
}

此代码显示了与OTG连接但未被佳能2900b接受为打印机设备的设备

0 个答案:

没有答案