How do Android devices get scanned contents of scan gun

Source: Internet
Author: User

1. bluetooth pairing, connecting the device

Turn on system settings, locate Bluetooth, open the sweep gun, and pair the scanner device. Enter a fixed pairing code, usually written in the Manual of the Scanner gun. After pairing is complete, the display device is connected. Just OK.

Configure permissions in 2.AndroidManifest

Add Bluetooth permissions to the Androidmanifest.xml file in your Android project.

    <uses-permission     android:name="android.permission.BLUETOOTH" />    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
3. Check the connection status of the scanner gun

Generally speaking, the scanning gun device is also equivalent to the normal external input device type, external keyboard.

My scan gun device returns the following Bluetooth type.

BluetoothClass.Device.Major.PERIPHERAL

In general, we can obtain information about our scanner equipment by the following way.

Set<BluetoothDevice> blueDevices = mBluetoothAdapter.getBondedDevices();if (blueDevices == null || blueDevices.size() <= 0) {    return false;}for (Iterator<BluetoothDevice> iterator = blueDevices.iterator(); iterator.hasNext(); ) {    BluetoothDevice bluetoothDevice = iterator.next();    if (bluetoothDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.PERIPHERAL) {        //TODO 获取扫码枪设备信息    }}

During the development process, it is necessary to determine whether the device is connected in real time.

Mbluetoothadapter.getbondeddevices ()

This method is only able to tell if the device has been paired. However, bindings do not represent connections, so they can only be discarded.

Public List getconnecteddevices (int profile)
public int getconnectionstate (Bluetoothdevice device, int. profile)

The two methods are then tried, but the method is available, but the device must be required to be sdk>18, that is, the Android 4.3 version is available.

Later turned to think, since the sweep gun is also input equipment, we can different Bluetooth device status detection start, instead of the input device detection start. So

private void hasScanGun() {    Configuration cfg = getResources().getConfiguration();    return cfg.keyboard != Configuration.KEYBOARD_NOKEYS;}

Get.

4. Get scan contents of scanner gun

Scanning gun, since it is an external input device, then it is natural, we start from KeyEvent.

Event resolution Classes

/** * Sweep Code Gun event resolution classes */public class Scangunkeyeventhelper {//delay 500ms, determine whether the scan code is complete.    Private final static long Message_delay = 500;    Sweep code Content Private StringBuffer Mstringbufferresult = new StringBuffer ();    Case-sensitive private Boolean mcaps;    Private Onscansuccesslistener Monscansuccesslistener;    Private Handler Mhandler = new Handler (); Private final Runnable mscanningfishedrunnable = new Runnable () {@Override public void Run () {p        Erformscansuccess ();    }    };        Returns the scan result private void performscansuccess () {String barcode = mstringbufferresult.tostring ();        if (Monscansuccesslistener! = null) monscansuccesslistener.onscansuccess (barcode);    Mstringbufferresult.setlength (0);        }//key event handling public void Analysiskeyevent (KeyEvent event) {int keycode = Event.getkeycode ();        Letter case to Judge Checkletterstatus (event); if (event.getaction () = = Keyevent.action_down) {Char Achar = GETINPUTCOde (event);;            if (Achar! = 0) {mstringbufferresult.append (Achar); } if (keycode = = Keyevent.keycode_enter) {//If enter, return directly to Mhandler.removecallbacks (                mscanningfishedrunnable);            Mhandler.post (mscanningfishedrunnable);                } else {//delay post, if within 500ms, there are other event mhandler.removecallbacks (mscanningfishedrunnable);            Mhandler.postdelayed (mscanningfishedrunnable, Message_delay);         }}}//check SHIFT key private void Checkletterstatus (KeyEvent event) {int keycode = Event.getkeycode (); if (keycode = = Keyevent.keycode_shift_right | | keycode = = keyevent.keycode_shift_left) {if (Event.geta            ction () = = Keyevent.action_down) {//press the SHIFT key to indicate uppercase Mcaps = true;            } else {//release SHIFT key to indicate lowercase mcaps = false; }}}//Get scan content private char GetinpuTcode (KeyEvent event) {int keycode = Event.getkeycode ();        Char Achar; if (keycode >= keyevent.keycode_a && keycode <= keyevent.keycode_z) {//Letter Achar = (ch AR) (mcaps?        ' A ': ' a ') + keycode-keyevent.keycode_a); } else if (keycode >= keyevent.keycode_0 && keycode <= keyevent.keycode_9) {//Digital ACha        R = (char) (' 0 ' + keycode-keyevent.keycode_0); } else {//other symbol switch (keycode) {case keyevent.keycode_period:a                    Char = '. ';                Break Case KeyEvent.KEYCODE_MINUS:aChar = mcaps?                    ‘_‘ : ‘-‘;                Break                    Case KeyEvent.KEYCODE_SLASH:aChar = '/';                Break Case KeyEvent.KEYCODE_BACKSLASH:aChar = mcaps?                    ' | ': ' \ \ ';                Break Default:achar = 0;            Break    }} return Achar;    } public interface Onscansuccesslistener {public void onscansuccess (String barcode); } public void Setonbarcodecatchlistener (Onscansuccesslistener onscansuccesslistener) {Monscansuccesslistener =    Onscansuccesslistener;        } public void OnDestroy () {mhandler.removecallbacks (mscanningfishedrunnable);    Monscansuccesslistener = null; }}

Override the Dispatchkeyevent method in activity to intercept the key event.

 /**     * Activity截获按键事件.发给ScanGunKeyEventHelper     *     * @param event     * @return     */    @Override    public boolean dispatchKeyEvent(KeyEvent event) {        if (isScanGunEvent(event)) {             mScanGunKeyEventHelper.analysisKeyEvent(event);            return true;        }        return super.dispatchKeyEvent(event);    }    /**     * 显示扫描内容     * @param barcode 条形码     */    @Override    public void onScanSuccess(String barcode) {        //TODO 显示扫描内容    }

Detailed code See: Https://github.com/czhzero/scangon

Note the point:

1. Some models cannot determine the external keyboard information, such as Samsung.

private void hasScanGun() {    Configuration cfg = getResources().getConfiguration();    return cfg.keyboard != Configuration.KEYBOARD_NOKEYS;}

Samsung mobile Cfg.keyboard The return value is equal to Configuration.keyboard_nokeys.

Therefore, for better compatibility, the following methods can be used,

/** * 判断是否已经连接扫码枪 * @return */protected boolean hasScanGun() {    Set<BluetoothDevice> blueDevices = mBluetoothAdapter.getBondedDevices();    if (blueDevices == null || blueDevices.size() <= 0) {        return false;    }    for (Iterator<BluetoothDevice> iterator = blueDevices.iterator(); iterator.hasNext(); ) {        BluetoothDevice bluetoothDevice = iterator.next();        if (bluetoothDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.PERIPHERAL) {            return isInputDeviceUsed(bluetoothDevice.getName());        }    }    return false;}private boolean isInputDeviceUsed(String deviceName) {    int[] deviceIds = InputDevice.getDeviceIds();    for (int id : deviceIds) {        if (InputDevice.getDevice(id).getName().equals(deviceName)) {            return true;        }    }    return false;}

If you are looking for a scanner that can be used for two development, please contact us and we will provide a complete download of the SDK package:

How do Android devices get scanned contents of scan gun

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.