Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android获取蓝牙设备列表

Android获取蓝牙设备列表的方法

作者:习作

这篇文章主要为大家详细介绍了Android获取蓝牙设备列表的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近换了一家公司,主要内容是做关于移动端室内定位的相关sdk,刚进来的时候信心满满,誓要干出一番天地!!!结果进来快一个多月了,根本没轮到我施展拳脚,给我搁置在一旁自己弄自己的。行吧,既然是做室内定位的话那无非就是(gps,蓝牙,wifi等)这些技术来实现嘛,然后我们就可以有本篇的切入点了:

android如何获取蓝牙设备了?

我们一步一步来分析,首先蓝牙属于一种短距离的无线通信技术,那作为我们android系统是否对此有过封装了?答案那肯定是有了!

BluetoothAdapter

android提供的蓝牙适配器,既然有了适配器,接下来我们获取蓝牙列表就有了一个切口。首先我们获取蓝牙列表之前,先需要获取蓝牙相关的权限,我们在AndroidManifest.xml里加入权限以下权限:

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

接下来我们在检查设备是否有蓝牙功能

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
   //通知用户当前设备不具有蓝牙功能
            return;
        }

如果bluetoothAdapter != null, 我们再来检查用户是否开启了蓝牙功能

if (!bluetoothAdapter.isEnabled()){ //检查是否开启蓝牙功能
     Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
     startActivity(intent); //跳转到系统Activity,让用户选择开启蓝牙功能
     bluetoothAdapter.enable();
     return;
}

通过BluetoothAdapter源码我们可以看到该类下面定义了很多常量值

public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
    public static final String ACTION_DISCOVERY_FINISHED = "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
    public static final String ACTION_DISCOVERY_STARTED = "android.bluetooth.adapter.action.DISCOVERY_STARTED";
    public static final String ACTION_LOCAL_NAME_CHANGED = "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
    public static final String ACTION_REQUEST_DISCOVERABLE = "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
    public static final String ACTION_REQUEST_ENABLE = "android.bluetooth.adapter.action.REQUEST_ENABLE";
    public static final String ACTION_SCAN_MODE_CHANGED = "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";

不难看出这些应该是适配器给我们配置的广播标签,那我们就根据这些状态值来创建一个

BroadcastReceiver.class用来接收蓝牙适配器给我们发送的消息

public class BlueToothBroadcast extends BroadcastReceiver {
 
    private List<String> blueToothList;
    private BlueToothListAdapter blueToothListAdapter;
    private List<String> stringList = new ArrayList<>;
 
    public BlueToothBroadcast(List<String> blueToothList,
BlueToothListAdapter blueToothListAdapter) {
        this.blueToothList = blueToothList;
        this.blueToothListAdapter= blueToothListAdapter;
    }
 
    @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);
                String mac = (device.getAddress().replace(":", ""));
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("设备名称:" + device.getName() + "\n");
                stringBuilder.append("mac地址:" + toLowerCase(mac, 0, mac.length()) + "\n");
                //用一个新的string集合去对比设备名称和mac地址,不能拼接rssi和uuid后再去对比
                if (stringList.indexOf(stringBuilder.toString()) == -1) {
                    // 防止重复添加
                    stringList.add(stringBuilder.toString());
                    if (device.getName() != null) {
                        stringBuilder.append("rssi:" + intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI) + "\n");
                        stringBuilder.append("Uuid:" + device.getUuids());
                        blueToothList.add(stringBuilder.toString()); // 获取设备名称和mac地址
                    }
                }
                Log.d("searchDevices", "onReceive str: " + blueToothList.toString());
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                //正在扫描
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                blueToothListAdapter.notifyDataSetChanged();
                Toast.makeText(context, "扫描完成", Toast.LENGTH_SHORT).show();
                break;
        }
    }
 
 
    //格式化mac地址
    public static String toLowerCase(String str, int beginIndex, int endIndex) {
        return str.replaceFirst(str.substring(beginIndex, endIndex),
                str.substring(beginIndex, endIndex)
                        .toLowerCase(Locale.getDefault()));
    }
}

接下来在activity中去注册我们的广播(记得在ondestroy中注销广播啊)

// 注册Receiver来获取蓝牙设备相关的结果
 broadcastReceiver = new BlueToothBroadcast(blueToothList,blueToothListAdapterr);
 IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(broadcastReceiver, intent);

最后一步,开启蓝牙发送广播,然后在自己写的适配器上把收集到的list加载上去,完事儿!

这套下来我们的蓝牙设备列表就获取完成了!快去试试

if (!bluetoothAdapter.isDiscovering()) {
            blueToothList.clear();
            addPairedDevice();//添加蓝牙配对设备
            bluetoothAdapter.startDiscovery();
 }
 
  private void addPairedDevice() {
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices != null && pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String mac = (device.getAddress().replace(":", ""));
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(getString(R.string.device_name)).append(device.getName()).append("\n");
                stringBuilder.append(getString(R.string.mac_ip)).append(toLowerCase(mac, 0, mac.length())).append("\n");
                stringBuilder.append(getString(R.string.uuid)).append(Arrays.toString(device.getUuids()));
                blueToothList.add(stringBuilder.toString());
            }
        }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文