Android实现蓝牙耳机连接

代码地址如下:
http://www.demodashi.com/demo/13259.html

前言

讲讲android对于蓝牙耳机连接技术的实现

今天涉及的内容有:
1. 流程讲解
2. 新建广播BluetoothReceiver,用于监听处理蓝牙连接过程中各状态
3. 在MainActivity中调用
4. 注意的点
5. 项目结构图和效果图

下面做以讲解

一. 流程讲解

在实现蓝牙耳机链接的时候,需要做一些前期工作,第一步,判断设备是否支持蓝牙。

1.1 设备是否支持蓝牙
   /**设备是否支持蓝牙**/
    public boolean isSupportBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            return true;
        }
        return false;
    }

若支持蓝牙,则需要判断设备蓝牙是否打开

1.2 设备蓝牙是否开启
    /**蓝牙是否已经启动**/
    public boolean isBluetoothOpen() {
        if (mBluetoothAdapter != null) {
            return mBluetoothAdapter.isEnabled();
        }
        return false;
    }

如果蓝牙没有开启,则需要请求开启蓝牙

1.3 请求开启蓝牙
   /**请求启动蓝牙**/
    public void requestStartBluetooth(int requestCode,Context context) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        ((MainActivity)context).startActivityForResult(enableBtIntent, requestCode);
    }

当然,蓝牙还有一个强制开启的方法:

    /**强制打开蓝牙**/
    public void openBluetooth(){
        if(isSupportBluetooth()){
            mBluetoothAdapter.enable();
        }
    }

蓝牙开启后,接下来是查询已配对过的设备

1.3 获取配对过的设备列表
   /**查询配对设备**/
    public List<BluetoothDevice> checkDevices() {
        List<BluetoothDevice> devices=new ArrayList<>();
        if(mBluetoothAdapter!=null){
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices != null && pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    devices.add(device);
                }
            }
        }
        return devices;
    }

若已配对列表中没有你的蓝牙耳机设备,则需要搜索

1.4 搜索新设备
    /**发现新设备**/
    public void findBluetoothDevice() {
        //其实是启动了一个异步线程,该方法将立即返回一个布尔值,指示发现是否已成功启动。
        // 发现过程通常涉及大约12秒的查询扫描,随后是每个找到的设备的页面扫描以检索其蓝牙名称
        if(mBluetoothAdapter!=null && mBluetoothAdapter.isEnabled() && !mBluetoothAdapter.isDiscovering()){
            if (mBluetoothAdapter.startDiscovery()) {
                LogUtil.i("=======已成功启动寻找新设备的异步线程=======");
            } else {
                LogUtil.i("=======启动寻找新设备的异步线程失败=======");
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值