Arjun Krishna Babu bio photo

Arjun Krishna Babu

Python. Machine Learning. Systems. Open source.

Email LinkedIn Github

It took me more than an acceptable amount of time to figure out how to make use of an Android phone’s built-in connectivity program to connect to a remote bluetooth device, and then get the reference of that BluetoothDevice in your app (in your MainActivity, for instance). And I’m kind of guessing I wasn’t the only on earth trying to do the same thing.

The official documentation on Bluetooth – while being pretty good – shows you how to reinvent the wheel and implement your own bluetooth-settings app rather than invoking the existing bluetooth settings which comes with nearly every Android phone out there.

And so, here I am, documenting on how exactly I managed to connect a bluetooth device to my phone using the phone’s native bluetooth interface, and then get the reference of that BluetoothDevice in your activity. Piece of cake, actually!

Basically, there are three things to take care of:

  1. Create an Intent that would open the bluetooth settings of your phone.
  2. Create a BroadcastReceiver to receive an intent. In this case, you’re specifically looking out for ‘BluetoothDevice.ACTION_ACL_CONNECTED’”
  3. Once the aforementioned intent has been received, an extra-field in it called ‘EXTRA_DEVICE’ can be used to extract the [BluetoothDevice] (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html) object of the remote object, using which you could establish commuunication between your phone and the remote device.

Given below is a sample application that would do what I have mentioned above (and nothing more. I have stripped off most of the irrelevant parts); comments have been provided in the relevant areas.

    package com.example.classiclogic.bluetoothconnector;

    import android.app.Activity;
    import android.bluetooth.BluetoothDevice;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.provider.Settings;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends Activity {

        private final String MYLOGTAG = "BluetoothConnectorLog";

        private Button ConnectButton;

        private Intent openBtSettings;
        private IntentFilter intentFilter;
        private BroadcastReceiver btBroadcastReceiver;
        private BluetoothDevice device;

        private void displayDeviceData()    {
            TextView nameView = (TextView) findViewById(R.id.tv_btname);
            TextView addrView = (TextView) findViewById(R.id.tv_btaddr);

            nameView.setText(device.getName());
            addrView.setText(device.getAddress());
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //broadcast receivet to receive intent
            btBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    String action = intent.getAction();

                    if( BluetoothDevice.ACTION_ACL_CONNECTED.equals(action) )   {

                        // Extract BluetoothDevice object referring to the remote object
                        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                        Log.v(MYLOGTAG, " Received: " + device.getName() + " " + device.getAddress());

                        displayDeviceData();
                    }
                }
            };

            ConnectButton = (Button) findViewById(R.id.connect_button);

            // Intent to open bluetooth settings of phone
            openBtSettings = new Intent();
            openBtSettings.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);

            intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);

            registerReceiver(btBroadcastReceiver, intentFilter);

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        protected void onStart() {
            super.onStart();

            ConnectButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v(MYLOGTAG, " Connect button pressed from MainActivity");
                    startActivity(openBtSettings);
                }
            });
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

Hope it helps! You could get the full code of the app (including the layout XML files, resources, and manifests) at my github account at https://github.com/arjunkbabu/BluetoothConnector_ANDROID .