16

In my project i have to read barcodes using barcode scanner Symbol CS3070 through bluetooth. i.e; i have to establish a connection between android device and barcode scanner through bluetooth. Can any one tell me how to read values from barcode reader and how to setup for communication? I've already read the Bluetooth Developer Guide, and I don't want to use Barcode Reader in Bluetooth Keyboard Emulation (HID) mode (I've some textview that can be filled using soft keyboard and Barcode Reader and I can't control the focus)

I'd use a thread like this to communicate with a reader

    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's 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) { }
    }
}

Thanks

Android84
  • 173
  • 1
  • 1
  • 6

1 Answers1

17

I just received my device and when I paired and connected the device it automatically sends the data to the currently focused EditText. What version of Android are you using because I tried it on ICS and JB and it worked this way. I have not tested it in any earlier versions.

Edit:

I downgraded my phone to Gingerbread and found out it does not work the same way but I have a solution:

This is important! >> First you must scan the barcode in the manual that says "Serial Port Profile (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);
    }
}

This is an incomplete version of my working code but you should get the gist.
I hope this solution works for you as well!

Brian Tacker
  • 1,091
  • 2
  • 18
  • 37
  • 1
    +1 Would you be able to append the complete code? I'm trying to use the same barcode reader in SPP mode. – Baz Apr 15 '13 at 15:19
  • 1
    The code I provided should suffice, you just need to know the address of the device. You can get it by calling getBondedDevices() after its been paired. Look here for more info: http://developer.android.com/guide/topics/connectivity/bluetooth.html – Brian Tacker Apr 16 '13 at 17:33
  • You would just use the TextView.setText() method and just pass it the data that you read from the socket – Brian Tacker Apr 20 '13 at 15:52
  • Ok, maybe I'm just not getting it, but how do I invoke the reading from the socket? Thanks so far! – Baz Apr 20 '13 at 15:56
  • 1
    When you call the socket = device.createRfcommSocketToServiceRecord(); then socket.connect(); it will attempt to connect to the scanner. Once its connected you create an InputStream with socket.getInputStream();. When you call Stream.read(); it will read wait until the scanner sends data. Once you scan something, it will read the bytes from the stream. Convert the byte array to a string and there's your data! I have noticed sometimes the scanner sends the \r separately so just keep that in mind. Hope that covers the confusion. – Brian Tacker Apr 21 '13 at 16:59
  • Ok, one more question. Would you connect to the socket once at the start of the activity and only close the connection when onPause is called or would you connect each time I want to use the scanner and close the connection right after that? – Baz Apr 22 '13 at 13:09
  • 1
    I would definitely not want to connect everytime I want to get data from the scanner. I would just stay connected and either have a "Done" button or like you said close the connection when onPause is called. – Brian Tacker Apr 22 '13 at 17:33
  • Small question about this code. I know the cs3070 keeps a list of barcodes on the device. Is it possible to retrieve al those barcodes at once using this code? I would like to scan a list on the scanner and then send it to the smartphone. – DavidVdd Sep 03 '13 at 14:40
  • I believe when you have the batch mode turned on it just stores each scan in a text file on the device itself. I'm not sure if there's a way to retrieve the list over the bluetooth connection, you'd have to check the documentation. Sorry I can't be of more assistance. – Brian Tacker Sep 03 '13 at 15:47
  • One query is that is Barcode Scanner Api dependent on Manufacturer OR this code will work with all Bluetooth Supported Barcode Scanner? Any suggestion? – Suresh Sharma Jan 07 '16 at 10:13
  • @SureshSharma I have not tried with any other manufacturer or model. But Im assuming different devices will give similar but possibly different outputs. – Brian Tacker Jan 08 '16 at 14:10
  • Thanks for the reply. Would you be able to list all near by Bluetooth barcode Scanner Device and Connect with one of them by selection and then communicate barcode with selected one? – Suresh Sharma Jan 14 '16 at 06:19
  • Great example, In addition i want to ask would this code be able to read data from all kind of Barcode Scanner (all brands). I am in the initial phase of developing an application. – Suresh Sharma Feb 08 '16 at 07:22