一个集成目前主流蓝牙的demo、android蓝牙4.0开发、项目中使用到了搜索BLE终端和读写BLE终端、另外还有在程序里面开房蓝牙、在Demo里面还处理了收到BLE终端数据交互的事件、代码里都有中文注释、要读性应该非常好的、应该会对开发有一定帮助、有兴趣的哥们可以下载看看
onCreate代码
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setTitle(R.string.title_devices); mHandler = new Handler(); // Use this check to determine whether BLE is supported on the device. Then you can // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); finish(); return; } //开启蓝牙 mBluetoothAdapter.enable(); mBLE = new BluetoothLeClass(this); if (!mBLE.initialize()) { Log.e(TAG, "Unable to initialize Bluetooth"); finish(); } //发现BLE终端的Service时回调 mBLE.setOnServiceDiscoverListener(mOnServiceDiscover); //收到BLE终端数据交互的事件 mBLE.setOnDataAvailableListener(mOnDataAvailable); }
收到BLE终端数据交互的事件
/** * 收到BLE终端数据交互的事件 */ private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){ /** * BLE终端数据被读的事件 */ @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) Log.e(TAG,"onCharRead " gatt.getDevice().getName() " read " characteristic.getUuid().toString() " -> " Utils.bytesToHexString(characteristic.getValue())); } /** * 收到BLE终端写入数据回调 */ @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { Log.e(TAG,"onCharWrite " gatt.getDevice().getName() " write " characteristic.getUuid().toString() " -> " new String(characteristic.getValue())); } };
最后给贴上Demo的源代码、希望对大家有用、有兴趣的哥们可以下载看看
源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1dDk9onZ 密码: 91qn
若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力
想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)
或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教
为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛