当前位置:   article > 正文

蓝牙配对和连接_flr bt dev

flr bt dev

最重要三个类:

BluetoothAdapter bluetoothAdapter

BluetoothSocket btSocket;

BluetoothDevice device



bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

bluetoothAdapter.startDiscovery();//开始搜索附近的蓝牙设备,搜索的时候会发出三个广播如下

startDiscovery()方法是一个异步方法,它会对其他蓝牙设备进行搜索,持续时间为12秒。搜索过程其实是在System Service中进行,我们可以通过cancelDiscovery()方法来停止这个搜索。在系统搜索蓝牙设备的过程中,系统可能会发送以下三个广播:ACTION_DISCOVERY_START(开始搜索),ACTION_DISCOVERY_FINISHED(搜索结束)和ACTION_FOUND(找到设备)。ACTION_FOUND这个才是我们想要的。所以在startDiscovery之前我们应该注册一个广播如下:

  1. IntentFilter intentfilter = new IntentFilter(
  2. BluetoothDevice.ACTION_FOUND);
  3. bluetoothReceiver = new BluetoothReceiver();
  4. // 注册bluetoothReceiver
  5. registerReceiver(bluetoothReceiver, intentfilter);

广播接收类BluetoothReceiver的实现如下:
  1. public class BluetoothReceiver extends BroadcastReceiver {
  2. @SuppressLint("ShowToast")
  3. public void onReceive(Context context, Intent intent) {
  4. String action = intent.getAction();
  5. Toast.makeText(MainActivity.this, "扫描中...", 100).show();
  6. // device对象代表被扫描到的远程设备的对象
  7. // 将搜索到的蓝牙设备在ListView中显示出来
  8. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  9. BluetoothDevice device = intent
  10. .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  11. String str = device.getName() + "|" + device.getAddress();
  12. if (lstDevices.indexOf(str) == -1)// 防止重复添加
  13. lstDevices.add(str); // 获取设备名称和mac地址
  14. adtDevices.notifyDataSetChanged();
  15. }
  16. }
  17. }

private List<String> lstDevices = new ArrayList<String>();

搜索到了之后就会把每一个蓝牙设备的name显示在一个listview中,点击listview中的某个设备之后,就会与之开始连接:

  1. String str = lstDevices.get(arg2);
  2. String[] values = str.split("\\|");
  3. String address = values[1];
  4. Log.e("address", values[1]);
  5. uuid = UUID.fromString(SPP_UUID);
  6. Log.e("uuid", uuid.toString());
  7. // btDev是远端的蓝牙设备,get到之后,用btsocket得到其中的socket,建立连接的套接字
  8. BluetoothDevice btDev = bluetoothAdapter.getRemoteDevice(address);
  9. try {
  10. btSocket = (BluetoothSocket) btDev
  11. .getClass()
  12. .getMethod("createRfcommSocket",
  13. new Class[] { int.class })
  14. .invoke(btDev, Integer.valueOf(1));
  15. } catch (IllegalAccessException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. } catch (IllegalArgumentException e) {
  19. // TODO Auto-generated catch block
  20. e.printStackTrace();
  21. } catch (InvocationTargetException e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. } catch (NoSuchMethodException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }
  28. // 取消查找
  29. bluetoothAdapter.cancelDiscovery();
  30. try {
  31. Toast.makeText(MainActivity.this, "正在连接...", Toast.LENGTH_SHORT)
  32. .show();
  33. btSocket.connect();
  34. Log.e(TAG,
  35. " BT connection established, data transfer link open.");
  36. Toast.makeText(MainActivity.this, "连接成功,进入控制界面",
  37. Toast.LENGTH_SHORT).show();
  38. // 打开控制界面
  39. Intent intent = new Intent(MainActivity.this,
  40. CtrlActivity.class);
  41. startActivity(intent);
  42. } catch (IOException e) {
  43. // TODO Auto-generated catch block
  44. e.printStackTrace();
  45. Log.e(TAG, " Connection failed.", e);
  46. Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT)
  47. .show();
  48. }


btSocket = btDev.createRfcommSocketToServiceRecord(SPP_UUID);

之前用这种方式给btSocket赋值时,btSocket.connect()就是抛出异常,后来改用如下方式就可以正常连接了

btSocket = (BluetoothSocket) btDev
                        .getClass()
                        .getMethod("createRfcommSocket",
                                new Class[] { int.class })
                        .invoke(btDev, Integer.valueOf(1));

注意在执行connect()操作之前一定要先

bluetoothAdapter.cancelDiscovery();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/192266
推荐阅读
相关标签
  

闽ICP备14008679号