安卓BLE蓝牙开发总结(一):BLE蓝牙的打开与搜索


前言

因为学习开发需要,最近学习BLE蓝牙的开发,总结了一下流程并说一下遇到的坑,这篇主要是安卓7.0以上的方法


一、获取安卓蓝牙权限

在AndroidManifest里面添加权限。


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

二、搜索蓝牙

1.布置控件

<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <Button
            android:id="@+id/bt_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索" />

        <TextView
            android:id="@+id/tv_status"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:text="未连接" />

        <ListView
            android:id="@+id/list_devicces"
            android:layout_width="match_parent"
            android:layout_height="400dp">

        </ListView>

    </LinearLayout>

</androidx.appcompat.widget.LinearLayoutCompat>

2.初始化控件并获取蓝牙适配器

public void initView(){
		//新版本的可以直接通过BluetoothAdapter获取,旧版本可能需要通过BluetoothManager;
		mAdapter = BluetoothAdapter.getDefaultAdapter();
        Button search = findViewById(R.id.bt_search);//搜索按钮
        search.setOnClickListener(this);
        tv_status = findViewById(R.id.tv_status);//状态栏
        tv_status.setOnClickListener(this);
        devices = findViewById(R.id.list_devicces);//搜索到的蓝牙列表
        devices.setOnItemClickListener(a);//这里的a绑定的是列表的item的监听,后面连接用的
    }

3.检测蓝牙并打开蓝牙

//首先判断是否支持蓝牙
if (!mAdapter.isEnabled()){
	Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);//这里是通过询问是否打开蓝牙
}
//也可以直接隐性打开
if (!mAdapter.isEnabled()){
	mAdapter.enable();
}

4.搜索蓝牙

1.ScanCallback回调函数 通过回调获取搜索到的结果

private ScanCallback callback = new ScanCallback() {
            @SuppressLint("HandlerLeak")
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onScanResult(int callbackType, ScanResult result//扫描结果) {
                super.onScanResult(callbackType, result);
                BluetoothDevice bluetoothDevice= result.getDevice();//获取扫描到的设备
                Log.d("TAG", "onScanResult: "+result.getDevice().getAddress());//显示获取到的设备mac地址
                //通过caontains方法,过滤已添加的device
                if (!deviceList.contains(bluetoothDevice) && bluetoothDevice.getName() != null) {
                   //通过两个List<>存储扫描到的信息
                    deviceList.add(bluetoothDevice);//deviceList存放蓝牙设备
                    deviceAll.add(bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress());// deviceAll存放蓝牙设备信息
                    Log.d("TAG1", "onLeScan: " + deviceList);
                    ArrayAdapter devicesAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, deviceAll);
                    devices.setAdapter(devicesAdapter);

                }
        };
        };

2.设置点击事件,开始搜索。

	@Override
    public void onClick(View v) {
        switch (v.getId()) {
            //开始搜索
            case R.id.bt_search:
                Thread scanThread = new Thread(new Runnable() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    @Override
                    public void run() {
                        deviceList.clear();   //重新搜索前把之前存储的设备信息清空
                        mAdapter.getBluetoothLeScanner().startScan(callback);//这里的callback就是ScanCallbak实例对象

                    }
                });
                scanThread.start();
                tv_status.setText("正在扫描");
                break;
        }
    }

到这里搜索BLE蓝牙就完成了


总结

这里会遇到一个API版本不符的Android lint问题,可以在函数前面加一个。

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//清除所有版本Api的Andrroid lint问题

一: 安卓BLE蓝牙开发总结(二):BLE蓝牙的连接
三: 安卓BLE蓝牙开发总结(三):接受和传输数据:BLE蓝牙的连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小周bb

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

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

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

打赏作者

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

抵扣说明:

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

余额充值