蓝牙相关内容,搜索设备

首先

private BluetoothAdapter mBluetoothAdapter;

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

 这个是最重要的,根据蓝牙适配器去操作

1.可以获得已经绑定的设备数据

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
    for (BluetoothDevice device : pairedDevices) {
            Toast.makeText(MainActivity.this
               ,device.getName() + ":" +device.getAddress()
               ,Toast.LENGTH_SHORT).show();
    }
}

2.可以广播监听搜索到的设备数据

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//搜索到设备
this.registerReceiver(receiver, filter);

filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索完
this.registerReceiver(receiver, filter);

广播回调

private final BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {//如果搜索到设备
                BluetoothDevice device =         
             intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获得设备
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//绑定状态为还没有被绑定
                    tvDevices.setText(device.getName() + ":" + device.getAddress() + "\n");
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                setProgressBarVisibility(false);
                setTitle("已搜素完成");
            }

        }
    };

3.搜索设备

setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描...");
if (mBluetoothAdapter.isDiscovering()) {//如果正在搜索,那就取消搜索
   mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();//开始搜索

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值