Connect to Bluetooth programmatically
Asked Answered
E

2

13

I'm trying to connect programmatically my device to for example on my Headsets... I had KitKat version and all worked perfect (Bluetooth always was connecting without problems autommatically) but since I've updated to Lolipop it doesn't. I'd like to know if there is any way to connect any paired device of my Android phone to Bluetooth when it turns on.

Since now I've this code (gets the Device name and Device Address) because I thought with it I could connect doing something like device.connect(MAC-Address); but it didn't work...

    BluetoothAdapter bluetoothAdapter
    = BluetoothAdapter.getDefaultAdapter();
Set < BluetoothDevice > pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
    for (BluetoothDevice device: pairedDevices) {
        mDeviceName.add(device.getName());
        mDeviceMAC.add(device.getAddress());

    }
}
bluetoothClass.setDeviceName(mDeviceName);
bluetoothClass.setDeviceMac(mDeviceMAC);

Question

On my MotoG (KitKat) if I turn my Bluetooth it connects autommatically to device (if it's near and paired ofc...) but on my LG G3 I must go to Configuration/Bluetooth/Paired devices/ and there tap the device to connect... and I want to avoid this... should be possible?


I would like to know if there is any possibility to connect to specific Bluetooth just adding the Device name or Device MAC... More or less like Android does when I click on my device to connect it connects autommatically... I just want to get that CLICK event. I know that Android should connect autommatically to a paired device but there's any exceptions that doesn not ... the only way to pair it it's doing the click... that's why I'm wondering if it's there a way to do it... I've read and tested kcoppock answer but it still don't work ..

Any suggestion?

EDIT

The main thing that I wanted to do is to connect my Bluetooth autommatically but since I've read on Hey you answer... I figured it out and I know it's an Android bug, so the thing that I would like to do is select the paired devices and then click on the device that I want to connect (Without doing any Intent) and connect it, instead to go Configuration/Bluetooth/.... Btw I've read any answers on StackOverflow and I found something with Sockets are they used to connect Bluetooth?Could be it a solution?

Errick answered 1/8, 2015 at 11:41 Comment(4)
@Heyyou Yes, sorry... I edited the questionSelfhypnosis
When I say I upgraded I meant that when I'm using another device witch is >5.0, so even if i,ve got the BT it takes soo long to connect and there are times that does not connect only when I open the BT list devices paired and click on the current BT device that I want to join in you got me?Selfhypnosis
Feel free to answer i'll test it and let you know if it works or not :)Selfhypnosis
My Lg g3 has 5.0 LolipopSelfhypnosis
P
11

Edit to answer latest question

You can avoid using an intent to search for paired devices. When connecting to a device that is not paired, a notification will pop up asking to pair the devices. Once paired this message should not show again for these devices, the connection should be automatic (according to how you have written your program).

I use an intent to enable bluetooth, and to make my device discoverable, I then set up my code to connect, and press a button to connect. In your case, you will need to ensure your accessories are discoverable also. In my case I use a unique UUID, and both devices must recognise this to connect. This can only be used if you are programming both devices, whether both are android or one android and one other device type.

Try this, and see if it solves your problem.


This answer is to the original question before it was edited to be another question.

I've edited my answer for clarity as I can see from the comments it is misleading. Your question has two parts.

On my MotoG (KitKat) if I turn my Bluetooth it connects autommatically to device (if it's near and paired ofc...) but on my LG G3 I must go to Configuration/Bluetooth/Paired devices/ and there tap the device to connect... and I want to avoid this... should be possible?

This is less of a programming issue and more of a platform issue.
There is a well documented bug in Android 5.0 with Bluetooth not automatically connecting and many other BT issues. These issues continue with all the updates on 5.0. versions and is not fixed until the 5.1. upgrade.

http://www.digitaltrends.com/mobile/android-lollipop-problems/11/

http://forums.androidcentral.com/lg-g3/473064-bluetooth-streaming-choppy-lg-3-lollipop.html

First port of call is to update to 5.1

These issues have been addressed in the Lollipop update 5.1

http://www.reddit.com/r/Android/comments/306m3y/lollipop_51_bluetooth/


Edit: I don't believe this is going to fix your problem of the automatic pairing, you wanted to know how to use BTGatt.

I've seen if I type device. to check what can I do it let me connectGatt() means /.../ But I can't figure it out how to do this...

To use BluetoothGatt

https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html

This class provides Bluetooth GATT functionality to enable communication with Bluetooth Smart or Smart Ready devices. /.../ GATT capable devices can be discovered using the Bluetooth device discovery or BLE scan process.

https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html

Here is a great example of how to use BluetoothGatt (it uses hear rate):
https://github.com/googlesamples/android-BluetoothLeGatt/blob/master/Application/src/main/java/com/example/android/bluetoothlegatt/BluetoothLeService.java

I have reproduced some of the code here, in case the link dies.

It basically follows similar lines to a regular bluetooth connection. You need to discover and find supported devices. Monitor state, etc.
These are the two most pertinent features to gatt.

The callback:

// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};

The broadcast:

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}

This question also has some relevant code that may help cut it down when learning:
BLuetooth Gatt Callback not working with new API for Lollipop

Now here's the rub. Are your devices bluetooth smart or smart ready?

This link gives a great list of smart devices. You will also find out when you implement your program.

http://www.bluetooth.com/Pages/Bluetooth-Smart-Devices-List.aspx

Puffery answered 5/8, 2015 at 18:35 Comment(12)
I'll test it tomorrow because now I don't have the Bluetooth device neither the LG g3 so tomorrow I'll let you know asap :) Thanks for the answer tho. Btw the BluetoothGatt it's used to connect paired devices?Selfhypnosis
hmmm I'll read about "smart devices" to see if it would work or not :PSelfhypnosis
I'm gonna test now if it works, is there any other way to connect BT without use BluetoothCatt?Selfhypnosis
Do I have to create the Callback on a service?Selfhypnosis
Okay, I know I've tested it on Samsung s4 (5.1) but it still... maybe I've formuled bad the question.... the most important think that I would like to do on my APP is connect autommatically, if it's not possible I would like to be able to see the Paired devices and then when I Click on it connect (Without make an Intent that goes to Bluetooth paired devices) is that possible?....Selfhypnosis
Did you find something?Selfhypnosis
you want to me to create another new question with a clear question? will you help me?Selfhypnosis
No I'm just programing an APP for a mobile the Bluetooth device it's a Parrot that it's installed on my car, so I just want if is there a possibility (main thing) get the event click for example when you are using a S4 when u turn on your BT a pop ups appears and u can click on a device, I want that click and if it's not possible get a list of paired (I've done this) but I don't have the connect function... you got me? I only program the app androidSelfhypnosis
Okay let me post another question I'll let you knwo when it's ready :) I'll explain better on my new one..Selfhypnosis
look at this is clearly? New questionSelfhypnosis
Helloo! Remember me? I've a question I'm working again with a bt stuff and I'd like to know if it's possible (I have a paired list devices) that if I click on a item list of that list it connects to it autommatically? Is that possible?Selfhypnosis
Yes i just want to know how to connext to bt with one click on any item paires of my listSelfhypnosis
D
12

This is how i made this work using Java Reflection and BluetoothProfile:

Attributes:

private boolean mIsConnect = true;
private BluetoothDevice mDevice;
private BluetoothA2dp mBluetoothA2DP;
private BluetoothHeadset mBluetoothHeadset;
private BluetoothHealth mBluetoothHealth;

Call:

mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.A2DP);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEADSET);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEALTH);

Listener:

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                mBluetoothA2DP = (BluetoothA2dp) proxy;
                try {
                    if (mIsConnect) {
                        Method connect = BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
                        connect.setAccessible(true);
                        connect.invoke(mBluetoothA2DP, mDevice);
                    } else {
                        Method disconnect = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
                        disconnect.setAccessible(true);
                        disconnect.invoke(mBluetoothA2DP, mDevice);
                    }
                }catch (Exception e){
                } finally {
                }
            } else if (profile == BluetoothProfile.HEADSET) {
                mBluetoothHeadset = (BluetoothHeadset) proxy;
                try {
                    if (mIsConnect) {
                        Method connect = BluetoothHeadset.class.getDeclaredMethod("connect", BluetoothDevice.class);
                        connect.setAccessible(true);
                        connect.invoke(mBluetoothHeadset, mDevice);
                    } else {
                        Method disconnect = BluetoothHeadset.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
                        disconnect.setAccessible(true);
                        disconnect.invoke(mBluetoothHeadset, mDevice);
                    }
                }catch (Exception e){
                } finally {
                }
            } else if (profile == BluetoothProfile.HEALTH) {
                mBluetoothHealth = (BluetoothHealth) proxy;
                try {
                    if (mIsConnect) {
                        Method connect = BluetoothHealth.class.getDeclaredMethod("connect", BluetoothDevice.class);
                        connect.setAccessible(true);
                        connect.invoke(mBluetoothHealth, mDevice);
                    } else {
                        Method disconnect = BluetoothHealth.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
                        disconnect.setAccessible(true);
                        disconnect.invoke(mBluetoothHealth, mDevice);
                    }
                }catch (Exception e){
                } finally {
                }
            }
        }
        public void onServiceDisconnected(int profile) {
        }
    };

I hope this helps anyone trying to connect to Bluetooth Audio devices and headsets.

Dozy answered 21/10, 2015 at 13:23 Comment(4)
I'll take a look when I have time thanks for the answer hexan :)Selfhypnosis
If I need some code more to make it works I'll let you know :DSelfhypnosis
No problem! :) You should just need to set mDevice and mBluetoothAdapter (BluetoothAdapter mBluetoothAdapter). If you need any more help don't hesitate.Dozy
Very nice. Thanks. Do you know where we can read about why you need "getDeclaredMethod" rather than calling the methods directly?Avril
P
11

Edit to answer latest question

You can avoid using an intent to search for paired devices. When connecting to a device that is not paired, a notification will pop up asking to pair the devices. Once paired this message should not show again for these devices, the connection should be automatic (according to how you have written your program).

I use an intent to enable bluetooth, and to make my device discoverable, I then set up my code to connect, and press a button to connect. In your case, you will need to ensure your accessories are discoverable also. In my case I use a unique UUID, and both devices must recognise this to connect. This can only be used if you are programming both devices, whether both are android or one android and one other device type.

Try this, and see if it solves your problem.


This answer is to the original question before it was edited to be another question.

I've edited my answer for clarity as I can see from the comments it is misleading. Your question has two parts.

On my MotoG (KitKat) if I turn my Bluetooth it connects autommatically to device (if it's near and paired ofc...) but on my LG G3 I must go to Configuration/Bluetooth/Paired devices/ and there tap the device to connect... and I want to avoid this... should be possible?

This is less of a programming issue and more of a platform issue.
There is a well documented bug in Android 5.0 with Bluetooth not automatically connecting and many other BT issues. These issues continue with all the updates on 5.0. versions and is not fixed until the 5.1. upgrade.

http://www.digitaltrends.com/mobile/android-lollipop-problems/11/

http://forums.androidcentral.com/lg-g3/473064-bluetooth-streaming-choppy-lg-3-lollipop.html

First port of call is to update to 5.1

These issues have been addressed in the Lollipop update 5.1

http://www.reddit.com/r/Android/comments/306m3y/lollipop_51_bluetooth/


Edit: I don't believe this is going to fix your problem of the automatic pairing, you wanted to know how to use BTGatt.

I've seen if I type device. to check what can I do it let me connectGatt() means /.../ But I can't figure it out how to do this...

To use BluetoothGatt

https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html

This class provides Bluetooth GATT functionality to enable communication with Bluetooth Smart or Smart Ready devices. /.../ GATT capable devices can be discovered using the Bluetooth device discovery or BLE scan process.

https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html

Here is a great example of how to use BluetoothGatt (it uses hear rate):
https://github.com/googlesamples/android-BluetoothLeGatt/blob/master/Application/src/main/java/com/example/android/bluetoothlegatt/BluetoothLeService.java

I have reproduced some of the code here, in case the link dies.

It basically follows similar lines to a regular bluetooth connection. You need to discover and find supported devices. Monitor state, etc.
These are the two most pertinent features to gatt.

The callback:

// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};

The broadcast:

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}

This question also has some relevant code that may help cut it down when learning:
BLuetooth Gatt Callback not working with new API for Lollipop

Now here's the rub. Are your devices bluetooth smart or smart ready?

This link gives a great list of smart devices. You will also find out when you implement your program.

http://www.bluetooth.com/Pages/Bluetooth-Smart-Devices-List.aspx

Puffery answered 5/8, 2015 at 18:35 Comment(12)
I'll test it tomorrow because now I don't have the Bluetooth device neither the LG g3 so tomorrow I'll let you know asap :) Thanks for the answer tho. Btw the BluetoothGatt it's used to connect paired devices?Selfhypnosis
hmmm I'll read about "smart devices" to see if it would work or not :PSelfhypnosis
I'm gonna test now if it works, is there any other way to connect BT without use BluetoothCatt?Selfhypnosis
Do I have to create the Callback on a service?Selfhypnosis
Okay, I know I've tested it on Samsung s4 (5.1) but it still... maybe I've formuled bad the question.... the most important think that I would like to do on my APP is connect autommatically, if it's not possible I would like to be able to see the Paired devices and then when I Click on it connect (Without make an Intent that goes to Bluetooth paired devices) is that possible?....Selfhypnosis
Did you find something?Selfhypnosis
you want to me to create another new question with a clear question? will you help me?Selfhypnosis
No I'm just programing an APP for a mobile the Bluetooth device it's a Parrot that it's installed on my car, so I just want if is there a possibility (main thing) get the event click for example when you are using a S4 when u turn on your BT a pop ups appears and u can click on a device, I want that click and if it's not possible get a list of paired (I've done this) but I don't have the connect function... you got me? I only program the app androidSelfhypnosis
Okay let me post another question I'll let you knwo when it's ready :) I'll explain better on my new one..Selfhypnosis
look at this is clearly? New questionSelfhypnosis
Helloo! Remember me? I've a question I'm working again with a bt stuff and I'd like to know if it's possible (I have a paired list devices) that if I click on a item list of that list it connects to it autommatically? Is that possible?Selfhypnosis
Yes i just want to know how to connext to bt with one click on any item paires of my listSelfhypnosis

© 2022 - 2024 — McMap. All rights reserved.