以编程方式连接到蓝牙 [英] Connect to Bluetooth programmatically

查看:41
本文介绍了以编程方式连接到蓝牙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式将我的设备连接到例如我的耳机...我有 KitKat 版本并且一切正常(Bluetooth 总是连接没有问题自动)但因为我已经更新到 Lolipop 它没有.我想知道是否有任何方法可以在打开时将我的 Android 手机 的任何配对设备连接到 蓝牙.

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.

自从现在我有了这个代码(获取设备名称和设备地址),因为我想用它我可以连接做类似 device.connect(MAC-Address); 的事情,但它没有'没工作...

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);

问题

在我的 MotoG (KitKat) 上,如果我打开 Bluetooth 它会自动连接到设备(如果它靠近并配对了...)但在我的 LG G3 上,我必须转到配置/蓝牙/配对设备/然后点击设备进行连接...我想避免这种情况...应该可以吗?

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?

我想知道是否有可能通过添加设备名称设备MAC来连接到特定的蓝牙......或多或少像Android 当我点击我的设备连接它时会自动连接...我只想得到那个 CLICK 事件.我知道 Android 应该自动连接到配对的设备,但有任何例外情况不会......配对它的唯一方法是点击......这就是为什么我想知道它是否在那里一种方法来做到这一点...我已经阅读并测试了 kcoppock 答案,但它仍然不起作用..

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 ..

有什么建议吗?

我想做的主要事情是自动连接我的 Bluetooth 但因为我已经阅读了 嘿你回答...我想通了,我知道这是一个Android错误,所以我想做的事情是选择配对设备 然后点击我想连接的设备(不做任何Intent)并连接它,而不是去Configuration/Bluetooth/....顺便说一句,我已经阅读了关于 StackOverflow 的任何答案,我发现了一些带有 Sockets 的东西,它们是用来连接 Bluetooth 的吗?这可能是一个解决方案吗?

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?

推荐答案

编辑以回答最新问题

您可以避免使用意图来搜索配对设备.当连接到未配对的设备时,会弹出通知要求配对设备.配对后,这些设备不应再次显示此消息,连接应该是自动的(根据您编写程序的方式).

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).

我使用 Intent 启用蓝牙,并使我的设备可被发现,然后我设置我的代码以进行连接,然后按下按钮进行连接.在您的情况下,您需要确保您的配件也可被发现.在我的情况下,我使用唯一的 UUID,并且两个设备都必须识别它才能连接.这只能在您对两种设备进行编程时使用,无论是 android 还是一种 android 和另一种设备类型.

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.

这个答案是对原始问题的,在它被编辑成另一个问题之前.

为了清楚起见,我已经编辑了我的答案,因为我从评论中可以看出它具有误导性.你的问题有两个部分.

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

在我的 MotoG (KitKat) 上,如果我打开蓝牙,它会自动连接到设备(如果它靠近并配对...)但在我的 LG G3 上我必须去到配置/蓝牙/配对设备/,然后点击设备以连接...我想避免这种情况...应该可以吗?

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?

这与其说是编程问题,不如说是平台问题.
Android 5.0 中存在一个详细记录的错误,蓝牙无法自动连接以及许多其他 BT 问题.这些问题在 5.0 上的所有更新中都会继续存在.版本,直到 5.1 才修复.升级.

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

首先要更新到 5.1

这些问题已在 Lollipop 更新 5.1 中得到解决

These issues have been addressed in the Lollipop update 5.1

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

我认为这不会解决您的自动配对问题,您想知道如何使用 BTGatt.

我已经看到我是否输入了设备.检查我能做什么让我connectGatt() 表示/.../但我不知道如何做到这一点...

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...

使用BluetoothGatt

https://developer.android.com/reference/android/bluetooth/蓝牙Gatt.html

此类提供蓝牙 GATT 功能以启用与 Bluetooth Smart 或 Smart Ready 设备通信./.../可以使用蓝牙设备发现支持 GATT 的设备发现或 BLE 扫描过程.

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

这是如何使用 BluetoothGatt(它使用听率)的一个很好的例子:
https://github.com/googlesamples/android-BluetoothLeGatt/blob/master/Application/src/main/java/com/example/android/bluetoothlegatt/BluetoothLeService.java

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.

它基本上遵循与常规蓝牙连接类似的路线.您需要发现并找到支持的设备.监控状态等
这是与 gatt 最相关的两个特性.

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.

回调:

// 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);
    }
};

广播:

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);
}

这个问题也有一些相关的代码,可以在学习的时候帮助减少:
BLuetooth Gatt 回调不适用于 Lollipop 的新 API

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

这篇关于以编程方式连接到蓝牙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆