Android 获取USB扫描枪扫描数据(无界面)

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

Android 平板热插拔USB扫描枪应用场景多,在有界面如EditText时,扫描枪扫描内容自动输入到编辑框了,在没有界面的情况下,怎么拿到扫描枪数据呢?

本文类似Android平台抢微信红包思路,使用强大的AccessibilityService(Google为了让Android系统更实用,为用户提供了无障碍辅助服务),但需要到系统设置->无障碍->服务 开启当前服务。

对AccessibilityService不了解的同学看看http://www.jianshu.com/p/4cd8c109cdfb

关键:标准扫描枪扫描数据会触发KEYCODE_ENTER键,感兴趣的同学可以在onKeyEvent函数里打log,看看这个扫描过程中出发的keyCode和条形码(或二维码)内容比较。

处理很简单,ScannerGunService(继承AccessibilityService),代码如下:

package com.android.accessibility; import com.android.accessibility.scanergun.ScannerGun;import com.android.accessibility.scanergun.ScannerGun.ScannerGunCallBack; import android.accessibilityservice.AccessibilityService;import android.content.Intent;import android.text.TextUtils;import android.util.Log;import android.view.KeyEvent;import android.view.accessibility.AccessibilityEvent;import android.widget.Toast; public class ScannerGunService extends AccessibilityService {     final static String TAG = "ScannerGunService";    private ScannerGun mScannerGun = null;     @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return START_STICKY;    }     @Override    public void onAccessibilityEvent(AccessibilityEvent arg0) {        // TODO Auto-generated method stub     }     @Override    public void onInterrupt() {        // TODO Auto-generated method stub     }     @Override    protected boolean onKeyEvent(KeyEvent event) {        // TODO Auto-generated method stub        if (event.getAction() == KeyEvent.ACTION_DOWN) {            int keyCode = event.getKeyCode();            if (keyCode <= 6) {                return false;            }            if (mScannerGun.isMaybeScanning(keyCode, event)) {                return true;            }        }        return super.onKeyEvent(event);    }     @Override    public void onCreate() {        // TODO Auto-generated method stub        mScannerGun = new ScannerGun(new ScannerGunCallBack() {             @Override            public void onScanFinish(String scanResult) {                // TODO Auto-generated method stub                if (!TextUtils.isEmpty(scanResult)) {                    Toast.makeText(ScannerGunService.this.getBaseContext(),                            "无界面监听扫描枪数据:" + scanResult, Toast.LENGTH_SHORT)                            .show();                }            }        });        mScannerGun.setMaxKeysInterval(50);        super.onCreate();    } }

ScannerGun相关处理就不在这里贴了,有兴趣下载 ScanGunAccessibility.zip

点这里可以跳转到人工智能网站

发表评论