Android BLE 蓝牙的一些总结

这篇博客总结了Android Bluetooth Low Energy (BLE)的使用,包括下载依赖库、初始化蓝牙、申请权限、搜索和连接蓝牙设备的过程。在Activity中,通过BleManager实例进行蓝牙操作,如在onResume中检查蓝牙状态并搜索设备。此外,还详细介绍了如何在ListView中显示搜索到的设备,并实现点击连接功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 https://github.com/Jasonchenlijian/FastBle

0.下载依赖库,添加库

1对蓝牙初始化和权限声明

1.1声明权限(AndroidManifest.xml中)

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

1.2在AndroidManifest.xml中还需要初始化蓝牙,我们新建一个class比如BleApplication,其中个代码如下:

 @Override
    public void onCreate() {
        super.onCreate();
        BleManager.getInstance().init(this);
        BleManager.getInstance()
                .enableLog(true)
                .setMaxConnectCount(7)
                .setOperateTimeout(5000);

1.3之后在AndroidManifest.xml中运用

<application
        android:name=".BleApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        ...
        ...
        ...
        ...

2.在Activity中写蓝牙搜索,连接的代码

可以用一个BleManager变量,因为之后会用到很多次BleManager.getInstance();

 private BleManager bleManager;

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bleManager = BleManager.getInstance();

 

2.1在生命周期onResume中 判断有无蓝牙连接,如果没有就开始检查蓝牙状态和搜索蓝牙.

这有三个方法checkBluetoothState(), searchBluetoothDevices(),showConnectedDevice()

 

@Override
    protected void onResume() {
        super.onResume();

        //检查蓝牙连接
        if (BleManager.getInstance().getAllConnectedDevice().size() == 0){
            checkBluetoothState();
            searchBluetoothDevices();
           
        }else
        {
            showConnectedDevice();
        }
    }

 

2.2几个方法的代码:

 2.2.1checkBluetoothState()

//检测蓝牙打开情况
    private void checkBluetoothState(){
        if (!bleManager.isBlueEnable()){
            //判断是否打开蓝牙
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值