JuiCe
JuiCe

Reputation: 4201

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(). 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.

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

Upvotes: 1

Views: 7252

Answers (1)

devunwired
devunwired

Reputation: 63303

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". The UUID is a value that must point to a published service on your embedded device, it can't just be randomly generated. 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.

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. 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. 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.

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

Upvotes: 4

Related Questions