18

I am getting a issue to send Commands from my android device to Bluetooth device.

Bluetooth is associated with a micro-controller. My effort is below:

    public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_ENABLE_BT = 2;
    private BluetoothAdapter mBluetoothAdapter;

    public static final String TAG = "CustomPOC BLEEEEEEE";
    private Button btn_send;
    private BluetoothDevice mdevice;
    private Handler mHandler;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        btn_send = (Button)findViewById(R.id.senddata);

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Log.i(TAG, "onClick - BT not enabled yet");
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        pairedOrNot();


        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectThread = new ConnectThread(mdevice);
                mConnectThread.start();
               // new ConnectAsynk(mdevice).execute();
            }
        });
    }

    private void pairedOrNot() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        List<String> s = new ArrayList<String>();
        for(BluetoothDevice bt : pairedDevices) {
            s.add(bt.getAddress());
            s.add(bt.getName());
            if("08:7C:BE:00:00:01".equals(bt.getAddress())) {
                mdevice = bt;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                Log.e(TAG, "wrong request code");
                break;
        }
    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;
            try {

                tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

                /*Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                tmp = (BluetoothSocket) m.invoke(device, 1);*/
                System.out.println("BTTTTTTTTTTT  Address   "+mmDevice.getAddress());
                BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mmDevice.getAddress());
//                Method m;
//                m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
//                tmp = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
            }
            catch (Exception e){
             e.printStackTrace();
            }
            mmSocket = tmp;
        }
        public void run() {
            mBluetoothAdapter.cancelDiscovery();

            try {
                mmSocket.connect();

                // Reset the ConnectThread because we're done
                synchronized (MainActivity.this) {
                    mConnectThread = null;
                }

                // Cancel the thread that completed the connection
                if (mConnectThread != null) {
                    mConnectThread.cancel();
                    mConnectThread = null;
                }

                // Cancel any thread currently running a connection
                if (mConnectedThread != null) {
                    mConnectedThread.cancel();
                    mConnectedThread = null;
                }

                 ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
                 mConnectedThread.start();
            } catch (IOException connectException) {
                try {
                    connectException.printStackTrace();
                    mmSocket.close();
                } catch (IOException closeException) { }

            } catch (Exception ex){
                ex.printStackTrace();
            }

        }
        public void cancel(){
            try {
                mmSocket.close();
            } catch (IOException e) { e.printStackTrace();}
        }

    }


    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { e.printStackTrace();}
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public void run() {
            byte[] buffer = new byte[1024];
            int begin = 0;
            int bytes = 0;
            while (true) {
                try {
                    bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
                    for(int i = begin; i < bytes; i++) {
                        if(buffer[i] == "1010101100000001000000100000000100001110".getBytes()[0]) {
                            mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
                            begin = i + 1;
                            if(i == bytes - 1) {
                                bytes = 0;
                                begin = 0;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Few heads-up that when i check connection status by

tmp.isConnected()

I found that it is returning a

false

value.

I want to send this command(1010101100000001000000010000000100001110) to external Bluetooth. But i am getting issue. Log trace is below at time launch of application:

08-17 07:48:39.718: W/art(14551): Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.
drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, 
android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable

When click on button btn_send, then i am getting below message in log trace:

08-17 07:51:32.046: W/BluetoothAdapter(14984): getBluetoothService() called with no BluetoothManagerCallback
08-17 07:51:38.448: W/System.err(14984): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:573)
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:584)
08-17 07:51:38.449: W/System.err(14984):    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:321)
08-17 07:51:38.449: W/System.err(14984):    at com.mahmad.custompoc11aug.MainActivity$ConnectThread.run(MainActivity.java:164)

and after debug i observe that issue is in this line

mmSocket.connect();

All required permission are given in manifest file.Please help me get rid this issue. Thanks in advance.

DJhon
  • 1,548
  • 3
  • 22
  • 39
  • The logcat output you attached is irrelevant because in your code all the exceptions are "silenced" - you catch them and do nothing. The very minimum you MUST do when catching exception is to log it (e.g. `e.printStackTrace()`). Please rerun your code with all the exceptions logged and then we might be able to help you – Vasiliy Aug 16 '16 at 05:05
  • Question updated. Please check it. – DJhon Aug 16 '16 at 06:14
  • And again - how can you know that no exception is being thrown along the way? Exceptions are thrown in order to notify you that something went wrong, but you just ignore them. Add `e.printStackTrace()` to all your `catch` clauses and post the entire logcat output. – Vasiliy Aug 16 '16 at 06:31
  • Thanks for reply, but above posted log trace is only showing in Studio trace. But after debug i found issue in line " mmSocket.connect();". Please help me or any suggestion would be appreciable. – DJhon Aug 16 '16 at 07:07
  • Please note that - I am using "RS232 Transfer protocol : 1200, N, 8, 1". – DJhon Aug 16 '16 at 08:16
  • How do you expect to get a solution if you don't do the minimum that I asked you for - print stack trace for all exceptions, rerun your code and post the entire logcat? – Vasiliy Aug 17 '16 at 09:09
  • Thanks for your support, please check updated question. Is here enough information for you. Please let me know. – DJhon Aug 17 '16 at 10:02
  • You can use this steps to send data. https://adhityareza.wordpress.com/2014/10/21/interfacing-android-with-microcontroller/ – Umut Catal Aug 17 '16 at 10:10
  • did you had a look here http://stackoverflow.com/questions/18657427/ioexception-read-failed-socket-might-closed-bluetooth-on-android-4-3 – Muhammed Refaat Aug 18 '16 at 11:41
  • Did you close your current connection ? like mSocket.close(); – Boldbayar Aug 19 '16 at 03:19
  • @Dilshad Can you post related code written for micro controller. Are you using Bluez? Also try fetching all SDP records using https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#fetchUuidsWithSdp() and see if the UUID you are using is present in it. – Sreejith Krishnan R Aug 19 '16 at 09:51

3 Answers3

2

I tried this library. You can try it also https://github.com/palaima/AndroidSmoothBluetooth

Umut Catal
  • 421
  • 4
  • 11
  • Above library has "Build issue". Thanks for help. I am trying to build it. When i get i chance, i will get back to you. – DJhon Aug 17 '16 at 11:25
1

I have a very simmilar code and it's working, maybe one of the main differences it that I'm doing a reset of threads:

// Reset the ConnectThread because we're done
            synchronized (blablabla.this) {
                mConnectThread = null;
            }

// Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

Just after you do:

mmSocket.connect();

hope it helps.

Hugo
  • 1,662
  • 18
  • 35
  • Thanks for your help, but its not working for me. Any further suggestion will be really helpful. After debug it has issue in this line "mmSocket.connect();" – DJhon Aug 16 '16 at 12:25
0

As you have mentioned that the issue is there on mmSocket.connect(); line hence, the problem is not while you are sending the command but creating a connection i.e. you are not able to retrieve a BluetoothSocket in opened or connected state.

What should you do ?

Try to use the below code with UUID , its valid for my bluetooth dongles.

UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); createInsecureRfcommSocketToServiceRecord(MY_UUID)

Let me know if this works for you.

Also check, https://stackoverflow.com/a/18786701/1503130

Community
  • 1
  • 1
Prateek
  • 3,923
  • 6
  • 41
  • 79