以编程方式连接到蓝牙

时间:2015-08-01 11:41:26

标签: android android-bluetooth

我尝试以编程方式将我的设备连接到例如我的耳机上...我有KitKat版本且一切都很完美(Bluetooth始终是自动连接而没有问题)但是我已更新为Lolipop它没有。我想知道是否有任何方法可以将我Android phone的任何配对设备连接到Bluetooth

从现在开始我已经使用了这段代码(获取了设备名称和设备地址),因为我认为我可以连接device.connect(MAC-Address);这样的东西,但它没有工作......

    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上我必须转到配置/蓝牙/配对设备/并点击设备连接......我想避免这种情况......应该可以吗?

我想知道是否有可能连接到特定的蓝牙,只需添加Device nameDevice MAC ...当我点击我的Android时更多或更少连接它的设备自动连接......我只是想得到那个CLICK事件。 我知道Android应该自动连接到配对的设备,但是有任何例外情况都没有...只有这样才能配对它进行点击...那就是&#39;为什么我想知道它是否有办法做到这一点...... 我已经阅读并测试了kcoppock answer但它仍然没有工作......

有什么建议吗?

修改

我想要做的主要事情是自动连接我的Bluetooth但是因为我已经阅读了Hey you回答......我想出来了,我知道它&#39;是一个Android错误,所以我想做的就是选择paired devices,然后点击我要连接的设备(不做任何Intent并连接它,而不是Configuration/Bluetooth/...。 顺便说一下,我已经在StackOverflow上阅读了任何答案,我发现Sockets的某些内容用于连接Bluetooth?可能是解决方案吗?

2 个答案:

答案 0 :(得分:10)

编辑以回答最新问题

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

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

试试这个,看看它是否解决了你的问题。

此答案是针对原始问题,然后才将其编辑为另一个问题。

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

  

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

这不是编程问题,而是更多的平台问题。
Android 5.0中存在记录良好的错误,蓝牙无法自动连接以及许多其他BT问题。这些问题将继续5.0上的所有更新。版本并且直到5.1才修复。升级。

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

中得到解决

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

修改 我不相信这会解决您自动配对的问题,您想知道如何使用BTGatt。

  

我看过是否输入设备。检查我能做什么让我   connectGatt()表示/.../   但我无法弄清楚如何做到这一点......

使用BluetoothGatt

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

  

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

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

我已经在这里复制了一些代码,以防链接死亡。

它基本上遵循与常规蓝牙连接类似的线路。您需要发现并找到支持的设备。 监控状态等。
这是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) + "\n" + stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}

这个问题也有一些相关的代码可能有助于在学习时减少它:
BLuetooth Gatt Callback not working with new API for Lollipop

现在,这就是问题所在。您的设备是蓝牙智能还是智能就绪?

此链接提供了一系列智能设备。您还可以了解实施计划的时间。

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

答案 1 :(得分:9)

这就是我使用Java Reflection和BluetoothProfile完成这项工作的方法:

属性:

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

呼叫:

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

监听器:

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

我希望这可以帮助任何人尝试连接蓝牙音频设备和耳机。