Android Bluetooth accept() / connect() with already paired devices

南笙酒味 提交于 2019-12-03 00:33:31
o.c.

In the client when I attempt to make a connection to a bonded device, I simply called it on the BluetoothDevice I found in BluetoothAdapter.getBondedDevices(). This does NOT work.

In order to properly establish the Bluetooth connection, I had to do something similar to the pseudocode below:

BluetoothDevice bonded = a device from BluetoothAdapter.getBondedDevices();
BluetoothDevice actual = BluetoothAdapter.getRemoteDevice(bonded.getAddress());

BluetoothSocket socket = actual.createRfcommSocketToServiceRecord(SOME_UUID);
socket.connect();

I arrived this answer by following exactly the Bluetooth chat example: Bluetooth Chat Service. Why it doesn't work on the device from getBondedDevices() is beyond me. Maybe someone with more intimate knowledge of Android can answer that.

Check out this example: http://developer.android.com/resources/samples/BluetoothChat/index.html.

this could explain how the bluetooth device connected and trans informations.

private static BluetoothSocket mSocket;
BluetoothDevice selectDevice = null;

void connectDevice(){
    if(mSocket == null) {
        //Log.d(TAG, "Socket is null");
        UUID SPP_UUID = UUID
                .fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
        Set<BluetoothDevice> bondedDevices = BluetoothAdapter
                .getDefaultAdapter().getBondedDevices();
        //Log.d(TAG, "Size: " + bondedDevices.size());
        /**
         * Select your divice form paired devices
         */
        for (BluetoothDevice bluetoothDevice : bondedDevices) {
            selectDevice = bluetoothDevice;
            //Log.d(TAG, bluetoothDevice.getName()+" "+bluetoothDevice.getAddress());
        }

        if(selectDevice.getBondState() == selectDevice.BOND_BONDED) {
            //Log.d(TAG, selectDevice.getName());
            try {
                mSocket = selectDevice.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                //Log.d(TAG, "socket not created");
                e1.printStackTrace();
            }
            try {
                mSocket.connect();
            } catch (IOException e) {
                try {
                    mSocket.close();
                    //Log.d(TAG, "Cannot connect");
                } catch (IOException e1) {
                    //Log.d(TAG, "Socket not closed");
                    e1.printStackTrace();
                }
            }
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!