简体   繁体   English

BluetoothSocket.connect()抛出IOException

[英]BluetoothSocket.connect() throws IOException

My program connects with a embedded bluetooth device which acts as the server. 我的程序与作为服务器的嵌入式蓝牙设备连接。 I successfully find the nearby bluetooth devices, but when I try to connect to the new device, my program crashes due to an IO Exception when calling BluetoothSocket.connect(). 我成功找到附近的蓝牙设备,但是当我尝试连接到新设备时,我的程序在调用BluetoothSocket.connect()时由于IO异常而崩溃。 I am having trouble figuring out what's going on so if someone could please help me out I'd really appreciate it. 我无法弄清楚发生了什么,所以如果有人能帮助我,我真的很感激。

I think it may have something to do with the UUID I randomly generate, but I'm not completely sure. 我认为它可能与我随机生成的UUID有关,但我不完全确定。

Thanks. 谢谢。

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnScanDevice = (Button) findViewById( R.id.scandevice );

    stateBluetooth = (TextView) findViewById( R.id.bluetoothstate );
    startBluetooth();

    listDevicesFound = (ListView) findViewById( R.id.devicesfound );
    btArrayAdapter = new ArrayAdapter<String>( AndroidBluetooth.this,
            android.R.layout.simple_list_item_1 );
    listDevicesFound.setAdapter( btArrayAdapter );

    CheckBlueToothState();

    btnScanDevice.setOnClickListener( btnScanDeviceOnClickListener );

    registerReceiver( ActionFoundReceiver, new IntentFilter( BluetoothDevice.ACTION_FOUND ) );

    listDevicesFound.setOnItemClickListener( new OnItemClickListener()
    {
      public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
      {
          myBtDevice = btDevicesFound.get( arg2 );
          try {
              btSocket = myBtDevice.createRfcommSocketToServiceRecord( MY_UUID );
              iStream = btSocket.getInputStream();
              oStream = btSocket.getOutputStream();
          } catch ( IOException e ) {
              Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
          } catch ( NullPointerException e ) {
              Log.e( "Bluetooth Socket", "Null Pointer One" );
          }
          myBtAdapter.cancelDiscovery();
          CheckBlueToothState();
          try {
              btSocket.connect();
          } catch ( IOException e ) {
              Log.e( "Bluetooth Socket", "IO Exception" );
          } catch ( NullPointerException e ) {
              Log.e( "Bluetooth Socket", "Null Pointer Two" );
          }
      } 

  });
}

private void CheckBlueToothState() {
    if( myBtAdapter == null ) {
        stateBluetooth.setText("Bluetooth NOT supported" );
    } else {
        if( myBtAdapter.isEnabled() ) {
            if( myBtAdapter.isDiscovering() ) {
                stateBluetooth.setText( "Bluetooth is currently " +
                        "in device discovery process." );
            } else {
                stateBluetooth.setText( "Bluetooth is Enabled." );
                btnScanDevice.setEnabled( true );
            }
        } else {
            stateBluetooth.setText( "Bluetooth is NOT enabled" );
            Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
            startActivityForResult( enableBtIntent, REQUEST_ENABLE_BT );
        }
    }
}

private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener() {
    public void onClick( View arg0 ) {
        btArrayAdapter.clear();
        myBtAdapter.startDiscovery();
    }
};


@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
    if( requestCode == REQUEST_ENABLE_BT ) {
        CheckBlueToothState();
    }
}

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
    public void onReceive( Context context, Intent intent ) {
        String action = intent.getAction();
        if( BluetoothDevice.ACTION_FOUND.equals( action ) ) {
            BluetoothDevice btDevice = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
            btDevicesFound.add( btDevice );
            btArrayAdapter.add( btDevice.getName() + "\n" + btDevice.getAddress() );
            btArrayAdapter.notifyDataSetChanged();
        }           
    }
};
public static void startBluetooth(){
    try {
        myBtAdapter = BluetoothAdapter.getDefaultAdapter();
        myBtAdapter.enable();
    } catch ( NullPointerException ex ) {
        Log.e( "Bluetooth", "Device not available" );
    }
}

public static void stopBluetooth() {
    myBtAdapter.disable();
}

There are two issues with the code you have posted, though only one is related to your crash. 您发布的代码存在两个问题,但只有一个与您的崩溃有关。

Most likely your crash in logcat says something like "Command rejected". 很可能你在logcat中的崩溃说的是“命令被拒绝”。 The UUID is a value that must point to a published service on your embedded device, it can't just be randomly generated . UUID是一个必须指向嵌入式设备上已发布服务的值, 它不能随机生成 In other words, the RFCOMM SPP connection you want to access has a specific UUID that it publishes to identify that service, and when you create a socket it must use the matching UUID. 换句话说,您要访问的RFCOMM SPP连接具有发布的特定UUID以标识该服务,并且在创建套接字时,它必须使用匹配的UUID。

This blog post I wrote may assist you in how you can query your device to get the proper UUID that needs to be inserted into your program. 我写的这篇博文可能会帮助您查询设备以获取需要插入程序的正确UUID。 Prior to Android 4.0 the SDK pretty much assumed you knew it ahead of time (you obtained it from the Bluetooth OEM, etc.) so discovering it from your device it a bit roundabout. 在Android 4.0之前,SDK几乎假设您提前知道它(您是从蓝牙OEM等处获得的),因此从您的设备发现它有点迂回。 If you are lucky enough to have a 4.0.3 device, fetchUuidsWithSdp() and getUuids() are now public methods you can call them directly to find all the published services and their associated UUID values. 如果你有幸拥有4.0.3设备, fetchUuidsWithSdp()getUuids()现在是公共方法,你可以直接调用它们来查找所有已发布的服务及其相关的UUID值。

The second issue with your code that will probably hit you later is that you cannot obtain the data streams from your socket until after you have connected, so you'll probably need to rewrite your method more like this: 您的代码可能会在以后遇到的第二个问题是,在连接之后,您无法从套接字获取数据流,因此您可能需要重写您的方法,如下所示:

      myBtDevice = btDevicesFound.get( arg2 );
      try {
          btSocket = myBtDevice.createRfcommSocketToServiceRecord( MY_UUID );
      } catch ( IOException e ) {
          Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
      }

      myBtAdapter.cancelDiscovery();
      CheckBlueToothState();
      try {
          btSocket.connect();
          //Get streams after connect() returns without error
          iStream = btSocket.getInputStream();
          oStream = btSocket.getOutputStream();
      } catch ( IOException e ) {
          Log.e( "Bluetooth Socket", "IO Exception" );
      } catch ( NullPointerException e ) {
          Log.e( "Bluetooth Socket", "Null Pointer Two" );
      }

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 bluetoothsocket.connect()在第二次运行时引发异常 - bluetoothsocket.connect() throws exception in the second run Android:BluetoothSocket连接抛出IOException - Android: BluetoothSocket connect throws IOException Android BluetoothSocket.connect()引发IOExceptions“连接被拒绝”和“服务发现失败” - Android BluetoothSocket.connect() throws IOExceptions “Connection Refused” and “Service discovery failed” BluetoothSocket.connect()引发异常“读取失败” - BluetoothSocket.connect() throwing exception “read failed” 我从来没有从BluetoothSocket.connect()中脱身 - I never get out from BluetoothSocket.connect() 带有Android 9的Samsung S9上BluetoothSocket.connect()失败 - BluetoothSocket.connect() fails on Samsung S9 with Android 9 BluetoothSocket.connect 不会抛出异常,但我没有连接 - BluetoothSocket.connect doesn't throw an exception, but I'm not connected Android AlertDialog 直到 bluetoothsocket.connect() 之后才会显示 - Android AlertDialog won't show until after bluetoothsocket.connect() 为什么在Toast.makeText()。show()之前调用BluetoothSocket.connect()? - Why is BluetoothSocket.connect() called before Toast.makeText().show()? Android BluetoothSocket :: connect()引发异常 - Android BluetoothSocket::connect() throws an exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM