蓝牙配对设备连接问题

时间:2013-08-27 12:55:14

标签: android sockets bluetooth

我遇到连接问题。除非我取消配对设备,否则它首先会起作用,而不是起作用。 我已经遇到了可能发生的每一个可能的异常,插座关闭,管道关闭,连接被拒绝,端口已经在使用等等。

我知道android 4.2(https://code.google.com/p/android/issues/detail?id=37725)上的蓝牙存在问题。

我在连接这些设备时遇到问题的设备:

  • Htc one(android 4.2)
  • samsung galaxy s2(android 4.1.2)
  • nexus 4(4.3)
  • samsung galaxy s4(4.2)

另一个小问题是,配对设备未存储(主要在nexus 4和sgs2上)。

这是我的代码:

private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //this is the other one that I've tried: fa87c0d0-afac-11de-8a39-0800200c9a66");

private static final String NAME = "BluetoothConnector";

public void listenForConnection() throws IOException, BluetoothException {
//first close the socket if it is open
closeSocket();

BluetoothServerSocket mServerSocket = null;
try {
    mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_SECURE); //ioexception here!         
} catch (IOException e) {
    if (Build.VERSION.SDK_INT >= 9) {
        try { //this is a stupid hack, http://stackoverflow.com/questions/6480480/rfcomm-connection-between-two-android-devices
            Method m = mBluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
            mServerSocket = (BluetoothServerSocket) m.invoke(mBluetoothAdapter, PORT);
        } catch (Exception ex) {
            Log.e(ex);
            throw e;
        }
    } else {
        throw e;
    }
}

while (!isCancelled) {
    try {
        socket = mServerSocket.accept();
    } catch (IOException e) {
        if (socket != null) {
            try {
                socket.close();
            } finally {
                socket = null;
            }
        }
        throw e;
    }

    if (socket == null) {
        throw new BluetoothException("Socket connection connected, but null");
    } else {
        isConnected = true;
        break; // everything is ok
    }
}
}



public void connect(String address) throws IOException, BluetoothException {
mBluetoothAdapter.cancelDiscovery();

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

try {
    socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e1) {
    Log.e(e1);

    if (Build.VERSION.SDK_INT >= 9) {
        try {
            Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
            socket = (BluetoothSocket) m.invoke(device, PORT);
        } catch (Exception e) {
            Log.e(e);
            throw e1;
        }
    } else {
        throw e1;
    }
}

// Make a connection to the BluetoothSocket
try {
    // This is a blocking call and will only return on a
    // successful connection or an exception
    socket.connect();
} catch (IOException e) {
    Log.e(e);
    // Close the socket
    try {
        socket.close();
    } catch (IOException e2) {
        Log.e(e2);
        Log.wtf("unable to close() socket during connection failure");
    }
    throw e;
}

}

private void closeSocket() {
    try {
        if (socket != null) {
            socket.close();
            socket = null;
            Log.d("Socket closed");
        }
    } catch (IOException e) {
        Log.e(e);
        Log.wtf("close() of connect socket failed");
    }
}

我尝试更改uuid(也是随机的),尝试查看较旧的sdk示例。 那么这里可能出现什么问题?

编辑:试图澄清:问题通常出现,当已经配对,连接的2个设备进行了一些成功的通信时,(由用户)断开连接。之后,除非重新启动或手动取消配对,否则无法重新连接。

2 个答案:

答案 0 :(得分:1)

  

您正试图以这种方式配对:

private void TwitPairedDevice() {
    buttonTwitPairDevice.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Set<BluetoothDevice> fetchPairedDevices=bluetooth.getBondedDevices();
            Iterator<BluetoothDevice> iterator=fetchPairedDevices.iterator();
            while(iterator.hasNext())
            {
                final BluetoothDevice pairBthDevice=iterator.next();
                final String addressPairedDevice=pairBthDevice.getAddress();
                AsyncTask<Integer, Void, Void> asynchPairDevice=new AsyncTask<Integer, Void, Void>() {

                    @Override
                    protected Void doInBackground(Integer... params) {
                        try {
                            socket=pairBthDevice.createRfcommSocketToServiceRecord(uuid);
                            socket.connect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    }
                };asynchPairDevice.execute();
            }
        }
    });
}
  

连接Pired Device:

    private void FetchPairedDevices() {
        Set<BluetoothDevice> pairedDevices=bluetooth.getBondedDevices();
        for(BluetoothDevice pairedBthDevice:pairedDevices)
        {
            listPairedDevice.add(pairedBthDevice.getName());
        }
        listviewPairedDevice.setAdapter(adapterPairedDevice);
        listviewPairedDevice.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                Object listPairedName=arg0.getItemAtPosition(arg2);
                String selectedPairedName=listPairedName.toString();
                Set<BluetoothDevice> bthDeviceChecking=bluetooth.getBondedDevices();
                for(final BluetoothDevice bthDevice:bthDeviceChecking)
                {
                    if(bthDevice.getName().contains(selectedPairedName))
                    {
                        listPairDevice.clear();
                        listPairDevice.add(bthDevice);
                        final String addressPairedDevice=bthDevice.getAddress();
                        AsyncTask<Integer, Void, Void> asynTask=new AsyncTask<Integer,Void,Void>() {
                            @Override
                            protected Void doInBackground(Integer... params) {
                                try {
                                    socket=bthDevice.createRfcommSocketToServiceRecord(uuid);
                                    socket.connect();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }
};
                        asynTask.execute(arg2);
                    }
                }
            }
        });
    }

答案 1 :(得分:1)

似乎此时蓝牙在Android上被破坏了。

无法确定连接2台设备的方法,这些设备始终有效。 Some people正在使用非官方的方式来执行此操作,但这并不适用于所有设备。

我做了一些内部测试,目前市场上排名前十的设备,所以在大约90次测试运行后,被黑客入侵的方法在75%的时间内工作,这还不够好。

例如,htc oneX将只处理传入的蓝牙请求,作为蓝牙免提设备(它成功连接!),但无法发送消息。

在实施完整的蓝牙功能后,我们决定将其从我们的应用中删除,并在没有它的情况下发布。我们将在稍后的版本中切换到wifi。