转载 ----Android学习笔记 - 蓝牙篇 (Bluetooth)
2024-09-07 05:09:27
1.什么是蓝牙
Bluetooth是目前使用的最广泛的无线通讯协议之一
主要针对短距离设备通讯(10米)
常用于连接耳机、鼠标和移动通讯设备等
2.发现周围蓝牙设备
BluetoothAdapter:代表了本地的蓝牙适配器
BluetoothDevice:代表一个远程的蓝牙设备
扫描已配对的蓝牙设备方法:
1.在AndroidManifest.xml声明蓝牙权限
<uses-permission Android:name="android.permission.BLUETOOTH" />
2.获得BluetoothAdapter对象
3.判断当前设备中是否拥有蓝牙设备
4.判断当前设备中蓝牙设备是否已经打开
5.得到已经配对的蓝牙设备对象
- BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
- if(btAdapter != null){
- if(btAdapter.isEnabled()){
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivity(intent);
- Set<BluetoothDevice> devices = adapter.getBondedDevices();
- if(devices.size() > 0){
- for(Iterator iterator = devices.iterator(); iterator.hasNext()){
- BluetoothDevice device = (BluetoothDevice)iterator.next();
- System.out.println(bluetoothDevice.getAddress());
- }
- }
- else System.out.println("没有绑定的蓝牙设备");
- }
- else System.out.println("蓝牙设备未正常启动");
- }
- else System.out.println("无蓝牙设备");
3.修改本机蓝牙设备的可见性
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //可见持续300秒,不能超过300秒
- startActivity(intent);
4.扫描周围可用的蓝牙设备
- //1.注册一个广播,用于接收“发现设备”的广播
- IntentFilter intentFilter = IntentFilter(BluetoothAdapter.ACTION_FOUND);
- BluetoothReceiver receiver = new BluetoothReceiver();
- registerReceiver(receiver, intentFilter);
- //2.创建蓝牙适配器,并开始扫描
- BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
- btAdapter.startDiscovery();
- //3.继续广播接收类,处理接收到的广播
- private class BluetoothReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent){
- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- System.out.println(device.getAddress());
- }
- }
最新文章
- [LeetCode] Remove K Digits 去掉K位数字
- 浅谈Android样式开发之shape
- c++中的重名问题
- Excel替换应用
- Unsupported configuration attributes: [FILE_UPLOAD]
- HDU 1372 Knight Moves (bfs)
- 算法实践——Twitter算法面试题(积水问题)的线性时间解法
- asp.net Linq 实现分组查询
- 面试时,问哪些问题能试出一个Android应用开发者真正的水平?
- wxsqlite3的加密模块单独编译
- Thinkphp的页面判断
- windows 下mysql的安装于使用(启动、关闭)
- ASP.NET MVC应用程序处理并发
- MYSQL:基础—存储过程
- HTML <;select>;标签
- hdu 3974 线段树 将树弄到区间上
- Ubuntu: Windows Help Tools For Ubuntu
- Samba文件共享系统
- C#泛型约束where T : class 解释
- 【ASP.Net MVC3 】使用Unity 实现依赖注入