无法连接蓝牙设备,错误:连接失败:读取失败,套接字可能关闭或超时,读取ret:-1

时间:2018-02-01 04:55:05

标签: android sockets bluetooth

我希望你没事。

我有一个应用程序,我希望通过蓝牙与Arduino板进行简单的连接,并将简单的命令发送到板上 为了测试,我首先尝试了两个Android设备的连接 这是我的代码:

btn_1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            try {
                findbt();
                Onbt();
            }
            catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            }


    });


void Onbt() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    //mysocket = mydevice.createRfcommSocketToServiceRecord(uuid);
    try {
        mysocket = mydevice.createRfcommSocketToServiceRecord(uuid);
    }
    catch (Exception e) {
        Log.e("tag", "Error creating socket");
    }
    try {
        mysocket.connect();
        Log("Connected");
    }
    catch (IOException e) {
        Log(e.getMessage());
        try {
            Log("trying fallback...");

            mysocket = (BluetoothSocket) mydevice.getClass().getMethod("createRfcommSocket", new Class[]{ int.class }).invoke(mydevice, 1);
            mysocket.connect();

            Log("Connected");
        }
        catch (Exception e2) {
            Log(e2.getMessage());
            Log("Couldn't establish Bluetooth connection!");
        }
        myoustream = mysocket.getOutputStream();
        myinputstream = mysocket.getInputStream();
        beginlisenfordata();

    }
}


private void Log(String message) {
    // TODO Auto-generated method stub
    TextView txt = (TextView) findViewById(R.id.textView1);
    txt.setText(txt.getText() + "\n" + message);
}


void findbt()
{
    myblutooth = BluetoothAdapter.getDefaultAdapter();
    if (myblutooth == null)
    {
        text_1.setText("any device not found");
    }
    if ( !myblutooth.isEnabled())
    {
        Intent enabledbt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enabledbt, 0);
    }
    Set<BluetoothDevice> pairDevices = myblutooth.getBondedDevices();
    Iterator iter = pairDevices.iterator();
    while (iter.hasNext()) {
        Log.i("tag", " device : " + iter.next());
    }
    //   mydevice = myblutooth.getRemoteDevice("10:D5:42:7C:85:08");
    mydevice = myblutooth.getRemoteDevice("3C:05:5C:B5:DC:4D");
    if (pairDevices.contains(mydevice))
    {
        text_1.setText("device is ready :" + mydevice.getName());
    }
}

但他在连线上给了我这个错误:

Connection failed: read failed, socket might closed or timeout, read ret: ‑1

我试过像fallback这样的方法,但是失败了 有人能帮助我吗?

我正在试用这个解决方案但不适合我!

Bluetooth Connection failed "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"

0 个答案:

没有答案