BluetoothSocket.connect()抛出IOException

时间:2012-06-11 19:25:43

标签: android exception io bluetooth

我的程序与作为服务器的嵌入式蓝牙设备连接。我成功找到附近的蓝牙设备,但是当我尝试连接到新设备时,我的程序在调用BluetoothSocket.connect()时由于IO异常而崩溃。我无法弄清楚发生了什么,所以如果有人能帮助我,我真的很感激。

我认为它可能与我随机生成的UUID有关,但我不完全确定。

感谢。

    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();
}

1 个答案:

答案 0 :(得分:3)

您发布的代码存在两个问题,但只有一个与您的崩溃有关。

很可能你在logcat中的崩溃说“命令被拒绝”。 UUID是一个必须指向嵌入式设备上已发布服务的值,不能随机生成。换句话说,您要访问的RFCOMM SPP连接具有它发布的特定UUID以识别该服务,并且当您创建套接字时,它必须使用匹配的UUID。

This blog post I wrote可以帮助您查询设备以获取需要插入程序的正确UUID。在Android 4.0之前,SDK几乎假设您提前知道它(您是从蓝牙OEM等处获得的),因此从您的设备发现它有点迂回。如果您有幸拥有4.0.3设备,fetchUuidsWithSdp()getUuids()现在是公共方法,您可以直接调用它们来查找所有已发布的服务及其相关的UUID值。

您的代码可能会在以后遇到的第二个问题是,在连接之后,您无法从套接字获取数据流,因此您可能需要更改这样的方法:

      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