蓝牙插座null

时间:2019-07-17 23:19:28

标签: java android android-studio bluetooth

我在一秒钟内多次调用一个函数,以将蓝牙数据从手机发送到arduino,但没有任何反应。因此,在我的代码中,我有一些调试代码可以找到问题,并且我认为这是蓝牙插座。这是我的代码:

@SuppressLint("ClickableViewAccessibility")
  private void setw() throws IOException {
    bluetooth_connect_device();
  }

  private void bluetooth_connect_device() throws IOException
  {
    try
    {
      myBluetooth = BluetoothAdapter.getDefaultAdapter();
      address = myBluetooth.getAddress();
      pairedDevices = myBluetooth.getBondedDevices();
      if (pairedDevices.size()>0)
      {
        for(BluetoothDevice bt : pairedDevices)
        {
          address=bt.getAddress().toString();name = bt.getName().toString();
          Toast.makeText(getApplicationContext(),"Connected", Toast.LENGTH_SHORT).show();

        }
      }

    }
    catch(Exception we){}
    myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
    btSocket.connect();
    try {}
    catch(Exception e){}
  }

  public void write(String s) throws IOException {
    try
    {
      Log.d("btSocket", String.valueOf(btSocket));
      if (btSocket != null)
      {
        byte[] msgBuffer = s.getBytes();
        btSocket.getOutputStream().write(msgBuffer);
      }
    }
    catch (Exception e)
    {
      Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }

日志显示 btSocket null,但是当我将 log.d 放入bluetooth_connect_device时,它不是null。

经过互联网上的大量研究,我找不到能正确回答我的问题的帖子。

谢谢。

0 个答案:

没有答案