Android蓝牙学习——搜索、配对、传文件(附源码)
导语
蓝牙作为一种成熟、低功耗无线通信技术的先锋,在可穿戴设备领域中扮演着越来越重要的作用。目前流行的蓝牙成功案例在运动手环、行车记录仪、终端解锁、智能家居等领域。接下来,一起动手敲代码吧~
源码下载:http://download.csdn.net/download/csdn_aiyang/9973522
添加权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
BluetoothAdapter
获取实例:BluetoothAdapter mBluetoothAdapter = BluetoothAdapter .getDefaultAdapter () ;
if (mBluetoothAdapter == null) {
Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
return;
}
常用方法:
- isEnabled() 判断系统蓝牙是否打开
- disable() 无弹窗提示关闭系统蓝牙
- enable() 无弹窗提示打开系统蓝牙(此操作有点不友好!)
- startDiscovery() 开始搜索设备 —–适合经典蓝牙和低功耗蓝牙两种
- cancelDiscovery() 取消搜索设备
- startLeScan() 开始搜索设备 —–适合扫描低功耗蓝牙,但是在api21以上被标记废弃使用
- stopLeScan() 停止搜索设备
- startScan() 开始搜索设备 —–api21以上扫描低功耗蓝牙,通过bluetoothAdapter.getBluetoothLeScanner()方法获取
- stopScan() 停止搜索设备
- stopScan() 停止搜索设备
注册广播监听
private IntentFilter makeFilters() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
return intentFilter;
}
BTBroadcastReceiver receiver = new BTBroadcastReceiver();
registerReceiver(receiver, makeFilters());
receiver.setBRInteractionListener(this);
然后在自定义广播类中进行拦截Action操作,再使用自定义接口与Activity进行交互数据信息显示。(可在源码中查看参考)
发送文本
/** * 蓝牙UUID */ public static UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothSocket bluetoothSocket =BluetoothDevice.createRfcommSocketToServiceRecord(Comment.SPP_UUID);
OutputStream outputStream =bluetoothSocket.getOutputStream();
outputStream.write(txtString.getBytes("utf-8"));
outputStream.flush();
相关地址下载:
GitHub:https://github.com/aiyangtianci/BluetoothAPP
码云:蓝牙demogiteehttps://gitee.com/AiYangDian/bluetoothdemo
还没有评论,来说两句吧...