android蓝牙编程问题

来源:互联网 发布:linux虚拟机 cpu 编辑:程序博客网 时间:2024/06/05 21:11

问题一:在Android蓝牙编程中,有时可以连接,有时不可以连接。不可以连接的原因是:在执行socket.connect()时,总抛出IOException:Unable to start service discovery.

刚开始我就直接百度找解决方案,可是都没有相关的解决方案,原以为是不稳定,并不是自己程序有问题。最后,还是看了看Android SDK  API,才发现问题在哪,在BluetoothSocket的对象执行connect()之前,必须保证结束发现设备,即保证BluetoothAdapter的对象已经执行cancelDiscovery()

问题二:可是在执行下面代码BluetoothRev类时,怎样才能执行到符合条件BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)的代码

因为刚开始接触到蓝牙,所以直接从网上找的代码。代码中只有

bluetoothDevices.removeAll(bluetoothDevices);
    bluetoothRev=new BluetoothRev();
    IntentFilter discoveryFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(bluetoothRev, discoveryFilter);

对于该问题我纠结了老半天,从网上也没找到答案,最后发现还得加上

 IntentFilter discoveryFilter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(bluetoothRev, discoveryFilter);

才能执行到符合条件BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)的代码

 private class BluetoothRev extends BroadcastReceiver{

  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action=intent .getAction();
   
   
   if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    // Get the BluetoothDevice object from the Intent
    device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    isfound=true;
    bluetoothDevices.add(device);
    Toast.makeText(MainActivity.this , device.getName(), 50).show();
    Toast.makeText(MainActivity.this , "已获取设备,可连接", 50).show();
    client.setText("停止");
   }
   else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
    if (isfound==false) {
     msg.setText("未发现设备,重新搜索");
    }
    else {
     msg.setText("发现设备");
    }
    adapter.cancelDiscovery();
    MainActivity.this.unregisterReceiver(this );
   }
  }
  
 }

0 0
原创粉丝点击