美文网首页
蓝牙之BluetoothAdapter

蓝牙之BluetoothAdapter

作者: xulj100 | 来源:发表于2023-08-04 22:09 被阅读0次

1. 接口定义

BluetoothAdapter:蓝牙适配器接口,用于管理蓝牙设备的连接和状态。它提供了方法来获取蓝牙设备的状态、启用/禁用蓝牙、搜索可用设备、连接/断开设备等。

2. 获取BluetoothAdapter

    private static BluetoothAdapter mBluetoothAdapter;

    /**
     * 获取 BluetoothAdapter
     *
     * @return BluetoothAdapter
     */
    public static BluetoothAdapter getBluetoothAdapter() {
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        return mBluetoothAdapter;
    }

3. 检测设备是否支持蓝牙

    /**
     * 检测设备是否支持蓝牙
     *
     * @return true:支持 ,false:不支持
     */
    public static boolean checkBluetoothEnable() {
        return getBluetoothAdapter() != null;
    }

4. 开启、关闭蓝牙

    /**
     * 获取当前蓝牙是否打开
     *
     * @return true:开启 ,false:关闭
     */
    public static boolean getBluetoothEnableState() {
        return getBluetoothAdapter().isEnabled();
    }

    /**
     * 设置蓝牙开关
     *
     * @param enable true:开启 ,false:关闭
     */
    public static void bluetoothEnable(boolean enable) {
        if (enable) {
            getBluetoothAdapter().enable();
        } else {
            getBluetoothAdapter().disable();
        }
    }

5. 获取当前蓝牙设备名称

    /**
     * 获取当前蓝牙设备名称
     */
    public static String getBluetoothName() {
        return getBluetoothAdapter().getName();
    }

6. 扫描附近蓝牙设备

    /**
     * 扫描设备
     */
    public static void startDiscovery() {
        if (!BluetoothUtil.getBluetoothAdapter().isDiscovering()) {
            getBluetoothAdapter().startDiscovery();
        }
    }

    /**
     * 取消扫描
     */
    public static void cancelDiscovery() {
        getBluetoothAdapter().cancelDiscovery();
    }

7. 获取已配对蓝牙设备

    /**
     * 获取已配对蓝牙设备
     *
     * @return Set
     */
    public static Set<BluetoothDevice> getBondedDevices() {
        return getBluetoothAdapter().getBondedDevices();
    }

8. 蓝牙配对、删除已配对设备

   /**
     * 与蓝牙设备进行配对
     *
     * @param device 蓝牙设备
     */
    public static void createBond(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            device.createBond();
        }
    }
    
    /**
     * 删除已配对蓝牙设备
     *
     * @param device 蓝牙设备
     */
    public static void removeBondDevice(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        try {
            Method method = device.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

9. 蓝牙连接、断开

    /**
     * 连接蓝牙
     *
     * @param device device
     * @return true:连接成功 , false:连接失败
     */
    public static boolean connectAllEnabledProfiles(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        try {
            Method discAcl = getBluetoothAdapter().getClass().getMethod("connectAllEnabledProfiles", BluetoothDevice.class);
            return (boolean) discAcl.invoke(getBluetoothAdapter(), device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 蓝牙断开连接
     *
     * @param device device
     * @return true:断开成功 , false:断开失败
     */
    public static boolean disconnectAllEnabledProfiles(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        try {
            Method discAcl = getBluetoothAdapter().getClass().getMethod("disconnectAllEnabledProfiles", BluetoothDevice.class);
            return (boolean) discAcl.invoke(getBluetoothAdapter(), device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

10. 蓝牙广播

    IntentFilter filter = new IntentFilter();
    // 当蓝牙适配器的状态发生变化时触发,可以获取当前的蓝牙状态(打开、关闭、打开中、关闭中)
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    // 开始扫描
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    // 扫描结束
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    // 扫描时发现新的蓝牙设备
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    // 当与远程设备的配对状态发生变化时触发,可以获取到设备的配对状态(已绑定、正在绑定、解绑等)
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    // 当与远程设备建立连接时触发,可以获取连接的设备对象。
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    // 当与远程设备断开连接时触发,可以获取断开连接的设备对象。
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    // 本地设备的蓝牙设备的名称变化
    filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
    requireActivity().registerReceiver(mReceiver, filter);

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BluetoothDevice.ACTION_FOUND:  // 扫描发现设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:  // 扫描完成
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:  // 设备绑定状态变化
                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:  // 设备开启关闭状态变化
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                    break;
                default:
                    break;
            }
        }
    };

最后贴上工具类

package com.hy.blue.util;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadsetClient;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;

public class BluetoothUtil {

    private static final String TAG = "BluetoothUtil";

    private static BluetoothAdapter mBluetoothAdapter;

    /**
     * 获取 BluetoothAdapter
     *
     * @return BluetoothAdapter
     */
    public static BluetoothAdapter getBluetoothAdapter() {
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        return mBluetoothAdapter;
    }

    /**
     * 检测设备是否支持蓝牙
     *
     * @return true:支持 ,false:不支持
     */
    public static boolean checkBluetoothEnable() {
        return getBluetoothAdapter() != null;
    }

    /**
     * 获取当前蓝牙是否打开
     *
     * @return true:开启 ,false:关闭
     */
    public static boolean getBluetoothEnableState() {
        return getBluetoothAdapter().isEnabled();
    }

    /**
     * 设置蓝牙开关
     *
     * @param enable true:开启 ,false:关闭
     */
    public static void bluetoothEnable(boolean enable) {
        if (enable) {
            getBluetoothAdapter().enable();
        } else {
            getBluetoothAdapter().disable();
        }
    }

    /**
     * 获取当前蓝牙设备名称
     */
    public static String getBluetoothName() {
        return getBluetoothAdapter().getName();
    }

    /**
     * 扫描设备
     */
    public static void startDiscovery() {
        if (!BluetoothUtil.getBluetoothAdapter().isDiscovering()) {
            getBluetoothAdapter().startDiscovery();
        }
    }

    /**
     * 取消扫描
     */
    public static void cancelDiscovery() {
        getBluetoothAdapter().cancelDiscovery();
    }

    /**
     * 获取已蓝牙蓝牙设备
     *
     * @return Set
     */
    public static Set<BluetoothDevice> getBondedDevices() {
        return getBluetoothAdapter().getBondedDevices();
    }

    /**
     * 与蓝牙设备进行配对
     *
     * @param device 蓝牙设备
     */
    public static void createBond(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            device.createBond();
        }
    }

    /**
     * 删除已配对蓝牙设备
     *
     * @param device 蓝牙设备
     */
    public static void removeBondDevice(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        try {
            Method method = device.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 连接远程设备
     *
     * @param device device
     * @return bool
     */
    public static boolean connect(BluetoothDevice device) {
        cancelDiscovery();
        if (device == null) {
            return false;
        }
        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            return connectAllEnabledProfiles(device);
        } else if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            return device.createBond();
        }
        return false;
    }

    /**
     * 连接蓝牙
     *
     * @param device device
     * @return true:连接成功 , false:连接失败
     */
    public static boolean connectAllEnabledProfiles(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        try {
            Method discAcl = getBluetoothAdapter().getClass().getMethod("connectAllEnabledProfiles", BluetoothDevice.class);
            return (boolean) discAcl.invoke(getBluetoothAdapter(), device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 蓝牙断开连接
     *
     * @param device device
     * @return true:断开成功 , false:断开失败
     */
    public static boolean disconnectAllEnabledProfiles(BluetoothDevice device) {
        if (device == null) {
            return false;
        }
        try {
            Method discAcl = getBluetoothAdapter().getClass().getMethod("disconnectAllEnabledProfiles", BluetoothDevice.class);
            return (boolean) discAcl.invoke(getBluetoothAdapter(), device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断蓝牙类型
     */
    public static int getBluetoothType(BluetoothDevice device) {
        BluetoothClass deviceClass = device.getBluetoothClass();
        return deviceClass.getDeviceClass();
    }
}


相关文章

网友评论

      本文标题:蓝牙之BluetoothAdapter

      本文链接:https://www.haomeiwen.com/subject/kzclkdtx.html