蓝牙
蓝牙通讯分为:经典蓝牙与低功耗蓝牙
现在所说的蓝牙设备,大部分都是在说4.0设备,ble也特指4.0设备。 在4.0之前重要的版本有2.1版本-基本速率/增强数据率(BR/EDR)和3.0 高速蓝牙版本,这些统称为经典蓝牙。
1.1 经典蓝牙
核心API:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
总结:
通过Android 系统提供API,进行蓝牙连接的前期工作准备(蓝牙开启,权限添加),外界设备扫描,设备连接(获取通讯BluetoothSocket),数据收发(IO流),资源释放 等等,完成Android系统与硬件设备通过蓝牙模式的数据收发功能。
1.1.1 权限检测:想要使用蓝牙必须给予应用相应的蓝牙权限
//需要此权限来执行任何蓝牙通信,如请求一个连接、接受一个连接和传输数据。
<uses-permission android:name="android.permission.BLUETOOTH"/>
//如果你想让你的应用启动设备发现或操纵蓝牙设置,必须申报bluetooth_admin许可
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
1.1.2 检测蓝牙是否开启:若没有开启,则跳转系统蓝牙功能相关选择开启蓝牙
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
1.1.3 设备扫描
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
蓝牙设备搜索的结果,Android系统会有对应的广播,我们可以在广播中对它进行接收并且进行相应的处理:
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
/**
* Create by dgs
* Description 处理蓝牙状态
**/
public class BluetoothStatuHandler implements IStatuHandler {
public static final String ACTION_BT_CONNECTED = "BT_CONNECTED";
public static final String ACTION_BT_DISCONNECTED = "BT_DISCONNECTED";
@Override
public void registAction(IntentFilter intentFilter) {
//=======================bluetooth========================= start
intentFilter.addAction(ACTION_BT_DISCONNECTED);
intentFilter.addAction(ACTION_BT_CONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
inten