android realizes the function of code scanning gun

  • 2021-12-21 04:58:58
  • OfStack

The code scanning effect of the code scanning gun is equivalent to keyboard entry, which will call back the dispatchKeyEvent keyboard pressing event.

Development environment: wired code scanning gun, supporting 2-D code

Code

STEP 1 Receive data


 /**
     *  Code scanning processing of code scanning gun 
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            int keyCode = event.getKeyCode();
            char aChar = (char) event.getUnicodeChar();
            if (aChar != 0) {
                mStringBufferResult.append(aChar);
            }
            mHandler.removeCallbacks(mScanningFishedRunnable);
            // If it is Enter key, return directly 
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                mHandler.post(mScanningFishedRunnable);
            } else {
                // Delay post If 500ms Inside, there are other events 
                mHandler.postDelayed(mScanningFishedRunnable, 500L);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

STEP 2 Process data


 /**
 * 2 Dimension code information object 
 */
   private QRCode qrCodeBean;
   /**
   * 2 Dimension code information original data container 
   */
   private StringBuilder mStringBufferResult = new StringBuilder();
   private Handler mHandler = new Handler();
   
   private Runnable mScanningFishedRunnable = new Runnable() {
        @Override
        public void run() {
            scanOk = false;
            String qrcode = mStringBufferResult.toString();
            if (!TextUtils.isEmpty(qrcode)) {
                //  Scan code to determine parameters 
                Gson gson = new Gson();
                try {
                    qrCodeBean = gson.fromJson(qrcode, QRCode.class);
                    //  Your code ...
                    //  If you want to support Chinese, the data can be used URLEncoder/URLDecoder Codec 
                } catch (JsonSyntaxException e) {
                    //  Parsing failed ...
                } catch (UnsupportedEncodingException e) {
                    //  Decoding failure ...
                } finally {
                    mStringBufferResult.setLength(0);
                }
            }
        }
    };

Reference: Android device Bluetooth connection scanning gun to obtain scanning content


Related articles: