以编程方式连接到蓝牙

Ski*_*ᴉʞS 13 android android-bluetooth

我正在尝试以编程方式将我的设备连接到例如我的耳机上...我有KitKat版本并且所有工作Bluetooth都很完美(总是自动连接没有问题)但是因为我已更新到Lolipop它没有.我想知道是否有任何方法可以将我的任何配对设备连接Android phoneBluetooth打开状态.

从现在开始我已经有了这个代码(获取设备名称和设备地址),因为我想它可以连接做类似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);
Run Code Online (Sandbox Code Playgroud)

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


我想知道是否有可能连接到特定的蓝牙只是添加Device nameDevice MAC...或多或少像Android当我点击我的设备连接它自动连接...我只想得到那个CLICK事件.我知道Android应该自动连接到配对的设备,但是有任何异常都没有...唯一的方法是配对它正在点击...这就是为什么我想知道它是否有办法做到这一点......我已经阅读并测试了kcoppock的答案,但它仍然无法正常工作..

有什么建议吗?

编辑

我想要做的主要是自动连接,Bluetooth但是因为我读过嘿你回答...我想出来了,我知道这是一个Android错误,所以我想要做的是选择paired devices和然后单击我要连接的设备(不做任何操作Intent)并连接它,而不是去Configuration/Bluetooth/....顺便说一下,我已经阅读了任何答案StackOverflow,我发现Sockets它们曾用于连接Bluetooth吗?可能是一个解决方案吗?

Yve*_*omb 11

编辑以回答最新问题

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

我使用意图启用蓝牙,并使我的设备可被发现,然后我设置我的代码进行连接,然后按一个按钮进行连接.在您的情况下,您还需要确保您的配件也可以被发现.在我的情况下,我使用一个唯一的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功能,以实现与蓝牙智能或智能就绪设备的通信./.../可以使用蓝牙设备发现或BLE扫描过程发现支持GATT的设备.

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

广播:

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);
}
Run Code Online (Sandbox Code Playgroud)

这个问题还有一些相关的代码,可能有助于在学习时减少它:
BLuetooth Gatt回调无法使用Lollipop的新API

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

此链接提供了一个很好的智能设备列表.您还可以了解实施计划的时间.

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


hex*_*xan 9

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

属性:

private boolean mIsConnect = true;
private BluetoothDevice mDevice;
private BluetoothA2dp mBluetoothA2DP;
private BluetoothHeadset mBluetoothHeadset;
private BluetoothHealth mBluetoothHealth;
Run Code Online (Sandbox Code Playgroud)

呼叫:

mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.A2DP);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEADSET);
mBluetoothAdapter.getProfileProxy(getApplicationContext() , mProfileListener, BluetoothProfile.HEALTH);
Run Code Online (Sandbox Code Playgroud)

监听器:

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) {
        }
    };
Run Code Online (Sandbox Code Playgroud)

我希望这有助于任何人尝试连接蓝牙音频设备和耳机.