Android工具类篇 蓝牙状态工具类 BlueToothUtils

/**
 * @author : Dumplings
 * @version : v1.0.0
 * @ClassName : BlueToothUtils.java
 * @Function :
 * @Description :
 * @Idea :
 * {@link :  }
 * @Encourage :And the more we try to understand one another, the more exceptional each of us will be.
 * 我们越是努力理解他人,自身也越发变得优秀。
 * @date : 2021/7/6
 */
public class BlueToothUtils {

    private Activity activity;
    private BluetoothAdapter bluetoothAdapter;
    //蓝牙是否可用
    private boolean bleEnable = false;

    public BlueToothUtils(Activity activity) {
        this.activity = activity;
        bleEnable = checkBlueToothEnable();
    }

    /**
     * 检测设备是否支持蓝牙
     */
    public boolean checkBlueToothEnable() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            ToastUtils.showShort("该设备不支持蓝牙");
            return false;
        } else {
            ToastUtils.showShort("该设备能支持蓝牙");
            return true;
        }
    }

    /**
     * 让用户去设置蓝牙
     */
    public void setBlueTooth() {
        if (bleEnable) {
            Intent blueTooth = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
            activity.startActivity(blueTooth);
        }
    }

    /**
     * 打开蓝牙
     */
    public void onBlueTooth() {
        if (bleEnable) {
            if (bluetoothAdapter.isEnabled()) {
                ToastUtils.showShort("蓝牙已打开,不用在点了~");
            } else {
                bluetoothAdapter.enable();
            }
        }
    }

    /**
     * 关闭蓝牙
     */
    public void offBlueTooth() {
        if (bleEnable) {
            if (bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.disable();
            } else {
                ToastUtils.showShort("蓝牙已关闭,不用在点了~");
            }
        }
    }

    /**
     * 获取已经配对的设备
     */
    public Set<BluetoothDevice> getConnectedDevices() {
        if (bleEnable) {
            if (bluetoothAdapter.isEnabled()) {
                return bluetoothAdapter.getBondedDevices();
            }
        }
        return null;
    }

    /**
     * 可发现模式
     * 默认情况下,设备的可发现模式会持续120秒。
     * 通过给Intent对象添加EXTRA_DISCOVERABLE_DURATION附加字段,可以定义不同持续时间。
     * 应用程序能够设置的最大持续时间是3600秒
     */
    public void discoverableDuration() {
        Intent discoverableIntent = new
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        //定义持续时间
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        activity.startActivity(discoverableIntent);
    }

    /**
     * 扫描蓝牙,会走广播
     */
    public void startDiscovery() {
        if (bleEnable) {
            if (!bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.startDiscovery();
            }
            ToastUtils.showShort("扫描蓝牙设备");
        }
    }

    /**
     * 停止扫描
     */
    public void stopDiscovery() {
        if (bleEnable) {
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();
            }
        }
    }

    /**
     * 扫描蓝牙
     */
    public void startScan() {
        if (bleEnable) {
            bluetoothAdapter.getBluetoothLeScanner().startScan(new ScanCallback() {
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    //信号强度,是负的,数值越大代表信号强度越大
                    result.getRssi();
                    super.onScanResult(callbackType, result);
                }

                @Override
                public void onBatchScanResults(List<ScanResult> results) {
                    super.onBatchScanResults(results);
                }

                @Override
                public void onScanFailed(int errorCode) {
                    super.onScanFailed(errorCode);
                }
            });
            ToastUtils.showShort("扫描蓝牙设备");
        }
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        if (bleEnable) {
            bluetoothAdapter.getBluetoothLeScanner().stopScan(new ScanCallback() {
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    super.onScanResult(callbackType, result);
                }

                @Override
                public void onBatchScanResults(List<ScanResult> results) {
                    super.onBatchScanResults(results);
                }

                @Override
                public void onScanFailed(int errorCode) {
                    super.onScanFailed(errorCode);
                }
            });
        }
    }

    /**
     * 连接设备
     */
    public void connectGatt(final BluetoothDevice device) {
        stopDiscovery();
        if (bleEnable) {
            device.connectGatt(activity, true, new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                    switch (status) {
                        case BluetoothGatt.GATT_SUCCESS:
                            //连接成功
                            break;
                        case BluetoothProfile.STATE_CONNECTED:
                            //发现蓝牙服务
                            break;
                    }
                    super.onConnectionStateChange(gatt, status, newState);
                }
            });
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的Android蓝牙通信的工具类,包含了搜索设备、连接设备、发送和接收数据的方法: ``` public class BluetoothUtils { private BluetoothAdapter bluetoothAdapter; private BluetoothSocket socket; private OutputStream outputStream; private InputStream inputStream; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final String TAG = "BluetoothUtils"; // 初始化蓝牙适配器 public BluetoothUtils() { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } // 判断蓝牙是否可用 public boolean isBluetoothAvailable() { if (bluetoothAdapter == null) { return false; } else { return true; } } // 打开蓝牙 public boolean enableBluetooth() { if (!bluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); context.startActivityForResult(intent, REQUEST_ENABLE_BT); return true; } else { return false; } } // 搜索蓝牙设备 public void searchDevices(final OnDeviceFoundListener onDeviceFoundListener) { final List<BluetoothDevice> devices = new ArrayList<>(); 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); devices.add(device); onDeviceFoundListener.onDeviceFound(device); } } }; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(receiver, filter); bluetoothAdapter.startDiscovery(); new Handler().postDelayed(new Runnable() { @Override public void run() { bluetoothAdapter.cancelDiscovery(); context.unregisterReceiver(receiver); onDeviceFoundListener.onSearchComplete(devices); } }, 10000); } // 连接蓝牙设备 public boolean connectDevice(BluetoothDevice device) { try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); outputStream = socket.getOutputStream(); inputStream = socket.getInputStream(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } // 发送数据 public void sendData(String data) { try { outputStream.write(data.getBytes()); } catch (IOException e) { e.printStackTrace(); } } // 接收数据 public String receiveData() { int bytes; byte[] buffer = new byte[1024]; try { bytes = inputStream.read(buffer); String data = new String(buffer, 0, bytes); return data; } catch (IOException e) { e.printStackTrace(); return null; } } // 关闭连接 public void closeConnection() { try { if (socket != null) { socket.close(); } if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } public interface OnDeviceFoundListener { void onDeviceFound(BluetoothDevice device); void onSearchComplete(List<BluetoothDevice> devices); } } ``` 使用方法: ``` BluetoothUtils bluetoothUtils = new BluetoothUtils(); // 搜索设备 bluetoothUtils.searchDevices(new BluetoothUtils.OnDeviceFoundListener() { @Override public void onDeviceFound(BluetoothDevice device) { // 搜索到设备 } @Override public void onSearchComplete(List<BluetoothDevice> devices) { // 搜索完成 } }); // 连接设备 bluetoothUtils.connectDevice(device); // 发送数据 bluetoothUtils.sendData(data); // 接收数据 String data = bluetoothUtils.receiveData(); // 关闭连接 bluetoothUtils.closeConnection(); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

其子昱舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值