Android 蓝牙开发(二)开启蓝牙,获取状态,发现设备。
来源:互联网 发布:周琦 知乎 编辑:程序博客网 时间:2024/06/05 17:25
(1)获取蓝牙相关权限。
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
(2)获取蓝牙状态。
获取蓝牙适配器:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
查看当前设备是否支持蓝牙:
if(bluetoothAdapter == null){ //("本机不支持蓝牙"); return; }
查看蓝牙是否已经打开:
if(!bluetoothAdapter.isEnabled()){ //("本机蓝牙未打开"); }
(3)打开蓝牙。
启用Intent,让系统开启蓝牙:
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent , REQUEST_ENABLE_BLUETOOTH);
在ActivityResult中处理结果:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BLUETOOTH){ //("蓝牙打开成功 "); } }(4)让本机蓝牙可以被其他蓝牙设备发现:
if(bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){ Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION , 300); startActivity(discoverableIntent); //("本机蓝牙 300 秒内可见"); }(5)查看已经配对过的蓝牙设备。
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); if(devices.size() > 0){ //处理}(6)开启发现周边蓝牙设备。
使用 adapter.startDiscovery() 方法来搜索设备,通过注册蓝牙相关广播监听,来获取和处理搜索结果。
相关监听广播有:
IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//发现蓝牙设备后的广播 IntentFilter startedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始搜索的广播 IntentFilter finishedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结束后的广播
当搜索到附近可用蓝牙设备后,通过:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);获取设备相关信息,如:
device.getName() //设备名称device.getAddress() //地址:如E3:34:23:D3:E2:98device.getBondState() // 设备的绑定状态device.getType() //设备的类型device.getBluetoothClass() // BluetoothClassdevice.getUuids() //uuid组
本文 Github 地址: https://github.com/huntervwang/BluetoothDemo
0 0
- Android 蓝牙开发(二)开启蓝牙,获取状态,发现设备。
- Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)
- android蓝牙开发:无法发现蓝牙设备的问题
- Android开发蓝牙篇之蓝牙设备开启、搜索周边蓝牙设备
- android之蓝牙通信(一)(检测蓝牙、开启蓝牙、扫描附近蓝牙设备)
- Android 蓝牙状态获取
- 蓝牙开启&& 被附近的其它蓝牙设备发现
- Android蓝牙开发教程(二)——连接蓝牙设备
- Android蓝牙开发(二)
- Android蓝牙开发(二)
- Android 获取蓝牙设备类型
- unity3d 获取蓝牙 状态 android
- Android蓝牙开发(二) BLE4.0低功耗蓝牙
- Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备(转)
- android 蓝牙ble设备开发
- Android之蓝牙开发初编(发现蓝牙,配对蓝牙,连接蓝牙)
- 蓝牙设备状态转换
- Android Bluetooth蓝牙开发(二)
- 关于Linux下的crypt加密
- Java笔试/面试题
- ForkJoinPool和ExecutorService实现1到10000的加法
- linux批量改文件中某一个字符串
- hive 自定义函数扩展
- Android 蓝牙开发(二)开启蓝牙,获取状态,发现设备。
- Oracel一些查看命令
- android 蓝牙通信(一)
- poj3126 bfs
- 1Activity+多个Fragment模式下进行横竖屏切换的问题及解决方式
- Codeforces Round #321 (Div. 2) A B C D
- java 堆、栈与数据类型
- iOS 代码实践总结
- 翻译-精通python设计模式-工厂模式