Android搜索附近蓝牙

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lvkaixuan/article/details/78624734

人人都是梦想家

1.首先添加蓝牙所需要的权限

    <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"/>

2.获取蓝牙适配器,并检查蓝牙是否打开,没有打开的话就询问用户是否打开

 //获取蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Log.d(TAG, "蓝牙是否打开: " + mBluetoothAdapter.isEnabled());
        //判断当前蓝牙是否打开
        if (!mBluetoothAdapter.isEnabled()) {
            //如果蓝牙处于关闭状态,弹出提示询问用户是否打开蓝牙
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, REQUEST_ENABLE);
        }

3.动态注册广播来接受搜索到的蓝牙信息

    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){//每扫描到一个设备,系统都会发送此广播。
                //获取蓝牙设备
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(scanDevice == null || scanDevice.getName() == null) return;
                Log.d(TAG, "搜索到了: name="+scanDevice.getName()+"  address="+scanDevice.getAddress());
            }
        }
    };

4.注册广播

    //注册广播搜索蓝牙
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        //发现设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //设备连接状态改变
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        //蓝牙设备状态改变
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothReceiver, filter);
    }

5.开始搜索

mBluetoothAdapter.startDiscovery();

6.停止搜索

mBluetoothAdapter.cancelDiscovery();

7.获取本机蓝牙详细信息

    //获取蓝牙详情
    private void getBlueToothDetail() {
        //获取本机蓝牙名称
        String name = mBluetoothAdapter.getName();
        //获取本机蓝牙地址
        String address = mBluetoothAdapter.getAddress();
        Log.d(TAG, "蓝牙名称: " + name + "蓝牙地址: " + address);
        //获取已配对蓝牙设备
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        Log.d(TAG, "已配对蓝牙数: " + devices.size());
        for (BluetoothDevice bonddevice : devices) {
            Log.d(TAG, "已配对蓝牙 name =" + bonddevice.getName() + " address" + bonddevice.getAddress());
        }
    }

Demo下载:https://fir.im/buletooth

源码:https://github.com/lvkaixuan/Bluetooth

效果图

这里写图片描述

展开阅读全文

没有更多推荐了,返回首页