Подтвердить что ты не робот

Как читать данные с помощью сканера штрих-кода Bluetooth Symbol CS3070 на Android-устройство

В моем проекте я должен читать штрих-коды, используя сканер штрих-кода Symbol CS3070 через bluetooth. то есть; я должен установить соединение между устройством Android и сканером штрих-кода через bluetooth. Может ли кто-нибудь сказать мне, как читать значения из считывателя штрих-кодов и как настроить связь? Я уже читал Руководство разработчика Bluetooth, и я не хочу использовать Barcode Reader в режиме эмуляции Bluetooth-клавиатуры (HID) (у меня есть текстовое представление, которое может заполняться с помощью мягкой клавиатуры и считывателя штрих-кодов, и я не могу контролировать фокус)

Я бы использовал такой поток, чтобы общаться с читателем

    private class BarcodeReaderThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public BarcodeReaderThread(UUID UUID_BLUETOOTH) {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BarcodeScannerForSGST", UUID_BLUETOOTH);
            /*
             * The UUID is also included in the SDP entry and will be the basis for the connection
             * agreement with the client device. That is, when the client attempts to connect with this device,
             * it will carry a UUID that uniquely identifies the service with which it wants to connect.
             * These UUIDs must match in order for the connection to be accepted (in the next step)
             */
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
                try {
                    // If a connection was accepted
                    if (socket != null) {
                        // Do work to manage the connection (in a separate thread)
                        InputStream mmInStream = null;

                        // Get the input and output streams, using temp objects because
                        // member streams are final
                        mmInStream = socket.getInputStream();

                        byte[] buffer = new byte[1024];  // buffer store for the stream
                        int bytes; // bytes returned from read()

                        // Keep listening to the InputStream until an exception occurs
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
                        if (bytes > 0) {
                            // Send the obtained bytes to the UI activity
                            String readMessage = new String(buffer, 0, bytes);
                            //doMainUIOp(BARCODE_READ, readMessage);
                            if (readMessage.length() > 0 && !etMlfb.isEnabled()) //Se sono nella parte di picking
                                new ServerWorker().execute(new Object[] {LEGGI_SPED, readMessage});
                        }
                        socket.close();
                    }
                }
                catch (Exception ex) { } 
            } catch (IOException e) {
                break;
            }
        }
    }

    /** 
     * Will cancel the listening socket, and cause the thread to finish
     */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

Спасибо

4b9b3361

Ответ 1

Я только что получил свое устройство, и когда я спарил и подключил устройство, он автоматически отправляет данные в текущий сфокусированный EditText. Какую версию Android вы используете, потому что я пробовал ее на ICS и JB, и это сработало. Я не тестировал его в предыдущих версиях.

Edit:

Я понизил свой телефон до Gingerbread и обнаружил, что он работает не так, но у меня есть решение:

Это важно! → Сначала вы должны сканировать штрих-код в руководстве, в котором говорится "Профиль последовательного порта (SPP)".

btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter.isEnabled())
{
    new BluetoothConnect().execute("");
}

public class BluetoothConnect extends AsyncTask<String, String, Void>
{
    public static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    @Override
    protected Void doInBackground(String... params)
    {
        String address = DB.GetOption("bluetoothAddress");
        BluetoothDevice device = btAdapter.getRemoteDevice(address);
        try
        {
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            btAdapter.cancelDiscovery();
            socket.connect();
            InputStream stream = socket.getInputStream();
            int read = 0;
            byte[] buffer = new byte[128];
            do
            {
                try
                {
                    read = stream.read(buffer);
                    String data = new String(buffer, 0, read);
                    publishProgress(data);
                }
                catch(Exception ex)
                {
                    read = -1;
                }
            }
            while (read > 0);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values)
    {
        if (values[0].equals("\r"))
        {
            addToList(input.getText().toString());
            pickupInput.setText("");
        }
        else input.setText(values[0]);
        super.onProgressUpdate(values);
    }
}

Это неполная версия моего рабочего кода, но вы должны получить суть.
Я надеюсь, что это решение будет работать и для вас!