在一家偏硬件的一家公司从事穿戴式设备的开发,通过近几个月学习与研究对于蓝牙4.0的通讯还有有点自己的见解,有不足的地方大家可以一起讨论,互相学习,废话不多说,那么如何进行蓝牙4.0的通讯与数据传输呢?本demo比较简单,大家应该都可以很好理解与学习的!
有基本的几个步骤,下面是一些代码段,希望对大家有所帮助吧。
添加蓝牙权限,
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
判断手机手机是否支持蓝牙ble
// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "设备不支持BLE 蓝牙", Toast.LENGTH_SHORT).show(); finish(); }
//获得蓝牙适配器对象BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
对于蓝牙的搜索过程采用广播:/** 因为蓝牙在搜索到设备和搜索完毕都是通过广播发送的,这里我们需要注册广播接收器 */ IntentFilter intentFilter = new IntentFilter( BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, intentFilter); intentFilter = new IntentFilter( BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(receiver, intentFilter); //注册蓝牙信号强度 intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); registerReceiver(receiver, intentFilter);
广播的注册:
//注册广播 private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); // 判断这个广播是否是蓝牙搜索到设备的广播 if (action.equals(BluetoothDevice.ACTION_FOUND)) { // 获取到传递过来的设备信息 BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { //信号强度 short rssi = intent.getExtras().getShort( BluetoothDevice.EXTRA_RSSI); String s = String.valueOf(rssi); mDeviceList.add(device.getName() + "\n" + device.getAddress() + "\n" + "信号强度:" + s +"dbm"); arrayAdapter.notifyDataSetChanged(); } // 判断是否为搜索完毕的广播 } else if (action .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { /***/ // setTitle("连接蓝牙设备"); bt_search.setText("搜索完毕"); }