【问题标题】:BluetoothSocket.connect() throws IOExceptionBluetoothSocket.connect() 抛出 IOException
【发布时间】:2012-06-14 17:21:01
【问题描述】:

我的程序与充当服务器的嵌入式蓝牙设备连接。我成功地找到了附近的蓝牙设备,但是当我尝试连接到新设备时,我的程序在调用 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();
}

【问题讨论】:

    标签: android exception io bluetooth


    【解决方案1】:

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

    您在 logcat 中的崩溃很可能会显示“命令被拒绝”之类的内容。 UUID 是一个必须指向嵌入式设备上已发布服务的值,它不能只是随机生成。换句话说,您要访问的 RFCOMM SPP 连接有一个特定的 UUID,它发布该 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

    【讨论】:

    • 非常感谢。不幸的是,我正在为这个应用程序使用 Android 2.0。我原本以为它会是一个特定的 UUID,但在任何地方都找不到。如果您知道在哪里看,或如何看,我将不胜感激。该应用程序在联想 Ideapad A1 上运行,并尝试连接到嵌入式 RN-41 蓝牙芯片。它也不仅仅连接到一个芯片,它应该能够连接到几个不同的芯片(不是同时,但你可以断开一个并找到另一个)。再次感谢
    • 所以...阅读博文,它会告诉你如何在 2.0 上做到这一点
    • 哈哈对不起,我在点击链接之前发布了这个,但我一直在阅读它。非常感谢您的帮助
    • 如果你再看一遍,我还是卡住了。我真的对 android 的结构不太满意,也不知道把你网站上给出的代码放在哪里。我问了另一个问题,如果你愿意去看看。
    • 你好 @devunwired 我有一个 RN4870 设备,我正在尝试使用 createRfcommSocketToServiceRecord() 方法连接它,但我收到“java.io.IOException:读取失败,套接字可能关闭或超时,每次都读取 ret: -1" ,它没有连接。另外,我想使用透明 UART 读取/写入数据。你能帮我解决这个问题吗?
    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2012-03-31
    • 2014-06-28
    相关资源
    最近更新 更多