Reader
object, get
an instance of UsbManager
by calling
Context.getSystemService()
.
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); Reader reader = new Reader(manager);
If you want to detect a card in your application, you can supply a
Reader.OnStateChangeListener
object to Reader
object.
reader.setOnStateChangeListener(new OnStateChangeListener() { @Override public void onStateChange(int slotNum, int prevState, int currState) { // TODO: Add your code here } });
To open a reader, you need to get a UsbDevice
object from
UsbManager
and request a permission to access the device or
discover a device using intent filter. For more information, please refer to
USB Host
from Android Dev Guide.
try { reader.open(device); } catch (IllegalArgumentException e) { e.printStackTrace(); }
It will throw IllegalArgumentException
if the
UsbDevice
object is not supported or it cannot be opened due to
communication error.
Android will not close the USB device automatically if you close the application. You cannot use the reader without unplugging it when you start the application next time. Therefore, it is advised to close the reader before closing the application.
reader.close();
Before transmitting APDU command, you need to power up a card first. The ATR string will be returned if the card is operated normally. Otherwise, it will throw a exception to indicate the error.
try { byte[] atr = reader.power(slotNum, Reader.CARD_WARM_RESET); } catch (ReaderException e) { e.printStackTrace(); }
After powering up the card, the card state is changed to Negotiable
(Reader.CARD_NEGOTIABLE
) or Specific
(Reader.CARD_SPECIFIC
). You cannot transmit a APDU command if the
card state is not equal to Specific. To select a protocol, invoke
Reader.setProtocol()
method with preferred protocols.
try { reader.setProtocol(slotNum, Reader.PROTOCOL_T0 | Reader.PROTOCOL_T1); } catch (ReaderException e) { e.printStackTrace(); }
After selecting the protcol, you can transmit the APDU command using
Reader.transmit()
.
byte[] command = { 0x00, 0x84, 0x00, 0x00, 0x08 }; byte[] response = new byte[300]; int responseLength; try { responseLength = reader.transmit(slotNum, command, command.length, response, response.length); } catch (ReaderException e) { e.printStackTrace(); }
You can control the reader using Reader.control()
if the reader
supports a set of escape commands.
// Get firmware version (ACR122) byte[] command = { 0xFF, 0x00, 0x48, 0x00, 0x08 }; byte[] response = new byte[300]; int responseLength; try { responseLength = reader.control(slotNum, Reader.IOCTL_CCID_ESCAPE, command, command.length, response, response.length); } catch (ReaderException e) { e.printStackTrace(); }@since 1.0