一、DetectionService 服务类
public class DetectionService extends AccessibilityService {
final static String TAG = "DetectionService";
private ScanGun mScanGun = 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 (mScanGun.isMaybeScanning(keyCode, event)) {
return true;
}
}
return super.onKeyEvent(event);
}
@Override
public void onCreate() {
mScanGun = new ScanGun(new ScanGun.ScanGunCallBack() {
@Override
public void onScanFinish(String scanResult) {
if (!TextUtils.isEmpty(scanResult)) {
Toast.makeText(DetectionService.this.getBaseContext(),
"无界面监听扫描枪数据:" + scanResult, Toast.LENGTH_SHORT).show();
LogUtil.e("无界面监听扫描枪数据:" + scanResult);
}
}
});
ScanGun.setMaxKeysInterval(50);
super.onCreate();
}
}
二、配置信息
<!--扫码配置-->
<service
android:name=".hardware.service.DetectionService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/detection_service_config" />
</service>
- detection_service_config.xml文件
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagRequestFilterKeyEvents"
android:canRequestFilterKeyEvents="true"
android:canRetrieveWindowContent="true"
android:description="@string/accessibility_service_description"
android:notificationTimeout="100" />
<string name="accessibility_service_description">Listen to USB scanner input</string>
<!--扫码权限-->
<uses-permission
android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions" />
三、使用方法
Intent service = new Intent(this, DetectionService.class);
startService(service);
注意:使用这个服务,必须要系统设置--》无障碍--》服务 在服务中在到你的软件,要打开这个服务才能使用,要不就使用不了