Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect and print from the USB printer from android

I'm creating an android app(API level 16 minimum) that could print a document from my android device, where printer is connected through USB. I found a code to detect USBfrom this link. I've attached my printer(HP Laserjet P1007) through USB. But it is not able to detect printer.

Edited

I've made some progress in detecting printer. I am able to detect printer. But still i am not able to print via bulk transfer. I've also tried to asynchronous transfer using method usbRequest.queue

And here's my code

public class MainActivity extends Activity {

private final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1008;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        setContentView(R.layout.activity_main);
        Log.i("Info", "Activity started");
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        if (deviceList.size() <= 0) {
            Log.i("Info", "No device found");
        } else {
            Log.i("Info", "Number of device : " + deviceList.size());
            ((TextView) findViewById(R.id.deviceCount))
                    .setText("No of device : " + deviceList.size());
        }
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        int count = 0;
        mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
                new Intent(ACTION_USB_PERMISSION), 0);
        while (deviceIterator.hasNext()) {
            count++;
            device = deviceIterator.next();
            Log.i("info", "Device No " + count + "........");
            Log.i("info", "Vendor id : " + device.getVendorId());
            Log.i("info", "Product id : " + device.getProductId());
            Log.i("info", "Device  name : " + device.getDeviceName());
            Log.i("info", "Device class : " + device.getClass().getName());
            Log.i("info", "Device protocol: " + device.getDeviceProtocol());
            Log.i("info", "Device subclass : " + device.getDeviceSubclass());
            if (device.getVendorId() == PRINTER_VENDOR_ID) {
                printer = device;
                break;
            }
        }

        findViewById(R.id.buttonPrint).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.i("Info", "Print command given");
                        IntentFilter filter = new IntentFilter(
                                ACTION_USB_PERMISSION);
                        registerReceiver(mUsbReceiver, filter);
                        if (printer != null) {
                            usbManager.requestPermission(printer,
                                    mPermissionIntent);
                        } else {
                            Log.e("Exception", "Printer not found");
                        }
                    }
                });

    } catch (Exception e) {
        Log.e("Exception", "Exception in onCreate " + e.getMessage());
        e.printStackTrace();
    }

}

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    final UsbDevice printerDevice = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(
                            UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (printerDevice != null) {
                            Log.i("Info", "Device permission granted");
                            startPrinting(printerDevice);
                        }
                    } else {
                        Log.d("Debug", "permission denied for device "
                                + printerDevice);
                    }
                }
            }
        } catch (Exception e) {
            Log.e("Exception", "Exception in onRecieve " + e.getMessage());
            e.printStackTrace();
        }
    }

};

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

        @Override
        public void run() {
            try {
                Log.i("Info", "Bulk transfer started");
                usbInterface = printerDevice.getInterface(0);
                UsbEndpoint endPoint = usbInterface.getEndpoint(0);
                conn = usbManager.openDevice(printer);
                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.i("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.i("Info", "Interface released");
                    conn.close();
                    Log.i("Info", "Usb connection closed");
                    unregisterReceiver(mUsbReceiver);
                    Log.i("Info", "Brodcast reciever unregistered");
                } catch (Exception e) {
                    Log.e("Exception",
                            "Unable to release resources because : "
                                    + e.getMessage());
                    e.printStackTrace();
                }
            }

        }
    });
}

}

And here's the log i'm getting

05-29 11:59:04.627: I/Info(5369): Print command given
05-29 11:59:04.657: I/Info(5369): Device permission granted
05-29 11:59:04.657: I/Info(5369): Bulk transfer started
05-29 11:59:04.657: D/UsbRequestJNI(5369): init
05-29 11:59:04.657: I/Info(5369): ??
05-29 11:59:04.657: I/Info(5369): Interface released
05-29 11:59:04.657: D/UsbDeviceConnectionJNI(5369): close
05-29 11:59:04.657: I/Info(5369): Usb connection closed
05-29 11:59:04.657: I/Info(5369): Brodcast reciever unregistered

But in printer side i'm not getting any response...

Thanks in advance for help.

like image 589
Bhupesh Avatar asked May 28 '14 05:05

Bhupesh


People also ask

Can I connect my phone to my printer via USB?

Connect one end of the USB cable to the printer and the other end to the USB OTG. Then connect the other end of the USB OTG to your Android phone. A plugin should pop-up on your Android phone. Tap “OK” to activate it for printing.

How do I get my Android phone to recognize my printer?

To connect your phone via the Default Print Service, go into the phone's settings, search for "printing", then select it from the results. Next, tap Printing in the list of Connection preferences, select Default Print Service and turn it on. A list of compatible printers on the network should appear.

How do I make my phone recognize my printer?

Start your mobile application and tap the Settings icon. (Mobile Cable Label Tool users must also tap [Printer Settings] - [Printer].) Select the printer listed under [Wi-Fi Printer]. You can now print wirelessly from your device.


1 Answers

Either use :

Intent i = new Intent(Intent.ACTION_VIEW);
i.setPackage("com.dynamixsoftware.printershare.amazon");
Uri myUri = Uri.parse(new File("file:///mnt/sdcard/download/ww.pdf").toString());
i.setDataAndType(myUri, "application/pdf");
startActivity(i);

OR https://github.com/pradeepksingh/Android-USB-printer

EDIT: See https://github.com/pradeepksingh/Android-USB-printer/blob/master/com/pradeep/adapter/USBAdapter.java#L72 for a good example.

like image 197
user1593373 Avatar answered Nov 03 '22 01:11

user1593373