Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

android - Connect to Bluetooth programmatically

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) + "
" + 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...