Wednesday, 23 January 2019

Read magnetic strip card data in Android

Recently I have developed an app with the purpose to read data from an USB card reader. The data to be read are stored on a plastic card organized in this way:
  1.  a start tag;
  2. a fixed field (length of 17 char);
  3. two other fields separated by a white space with no size declarad but always present;
  4. an end tag. 
The external USB card reader is something similar to an external keyboard so it's possible to override the appropriate method in the  Activity to handle every single character read from the reader.
The Activity manages the card data character by character so  firstly I had to create a UsbDecoder class to manage the data flow and to build my output values. Lastly. I had to implemented the onKeyDown to intercept the data from the reader:

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        char pressedKey;
        if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE || event.getKeyCode() == KeyEvent.KEYCODE_TAB) {
            pressedKey = Character.SPACE_SEPARATOR;
        } else {

            pressedKey = (char) event.getUnicodeChar();
        }
        if (usbDecoder.addChar(pressedKey)) {
          #do somethings, data are available
        }

        return true;
    }

Unfortunately, the sequence of characters intercepted by this method had some issues as, for example, the fact that the white space was not passed to this method. After several attempts I found a workaround due to the fact that a space charachter is passed to onKeyUp method:


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        char pressedKey;
        if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE || event.getKeyCode() == KeyEvent.KEYCODE_TAB) {
            pressedKey = Character.SPACE_SEPARATOR;
            usbDecoder.addChar(pressedKey);
        }

        return true;
    } 
 

No comments:

Post a Comment