Android中蓝牙的简单使用

1、
声明蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

2、
 关键代码:
 获取到蓝牙适配器
 BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
 bluetoothAdapter.isEnabled(); // 判断蓝牙是否开启
 bluetoothAdapter.enable();// 打开蓝牙
 bluetoothAdapter.disable();// 关闭蓝牙 
 bluetoothAdapter.startDiscovery();// 开始扫描

3、动态注册一个广播来接收扫描到的蓝牙设备
    private BroadcastReceiver blueToothReceiver = new BroadcastReceiver() {        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                // 每当扫描到蓝牙设备,都会被触发
                case BluetoothDevice.ACTION_FOUND:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    refresh(device); // 将扫描到的蓝牙添加到ArrayList中
                    break;
            }
        }
    };
    
    // 动态注册广播
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    registerReceiver(blueToothReceiver, filter);
    //这里是使用RecycleView进行显示的
    public void refresh(BluetoothDevice device) {
        if (!mDevices.contains(device)) {
            mDevices.add(device);// 需要对该设备进行判断,因为该设备可能在之前已经被添加到集合中了,那么则不用再进行添加
            adapter.notifyDataSetChanged(); 
        }
    }
4、连接蓝牙
    private OutputStream outputStream;
    /**
     *   蓝牙的连接也是耗时操作,与访问网络差不多,所以需要创建子线程进行执行
     */
    private void connect (final BluetoothDevice device) {
        new Thread() {
            public void run() {
             try {
             BluetoothSocket bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("服务器的UUID"));
             bluetoothSocket.connect();// 连接
             outputStream = bluetoothSocket.getOutputStream();// 拿到输出流, 就可以往蓝牙服务端写东西了
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    } 

      个人浅见,有错误请帮忙指出,谢谢!

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值