android 蓝牙搜索、配对连接通信总结

这篇博客总结了Android平台下蓝牙搜索、配对连接的实现步骤。首先通过动态注册广播接收者来搜索蓝牙设备,然后利用反射方法进行蓝牙配对。在配对成功后,通过蓝牙套接字进行通信,模拟Socket网络编程,使用多线程读取数据流,实现蓝牙串口通信。
摘要由CSDN通过智能技术生成

 

蓝牙协议可以实现一个蓝牙设备和6到8个蓝牙设备进行通信。

1、蓝牙搜索的实现

利用蓝牙的发现和完成动作动态注册广播接受者获得蓝牙设备。

第一步,获得蓝牙适配器

BluetoothAdapter mBtAdapter= BluetoothAdapter.getDefaultAdapter();
<span style="white-space:pre">	</span>// 判断蓝牙是否打开
<span style="white-space:pre">				</span>if (!mAdapter.isEnabled()) {
<span style="white-space:pre">					</span>mAdapter.enable();

第二步动态注册蓝牙搜索广播接收者

  // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

并且可以利用意图过滤器设置广播的优先级

 filter.setPriority(Integer.MAX_VALUE);

对应的广播接收者:

 // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };

或者利用发现和完成动作定义两个广播接受者,在完成的动作中注销广播接收者。

关键代码如下:

/**
	 * 接收器 当搜索蓝牙设备完成时调用
	 */
	private BroadcastReceiver _foundReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			BluetoothDevice device = intent
					.getPar
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值