Android BLE开发之Android手机与BLE终端通信

接下来贴出本文核心代码:

public class DeviceScanActivity extends ListActivity {private final static String TAG = DeviceScanActivity.class.getSimpleName();private final static String UUID_KEY_DATA = "0000ffe1-0000-1000-8000-00805f9b34fb";private LeDeviceListAdapter mLeDeviceListAdapter;/**搜索BLE终端*/private BluetoothAdapter mBluetoothAdapter;/**读写BLE终端*/private BluetoothLeClass mBLE;private boolean mScanning;private Handler mHandler;// Stops scanning after 10 seconds.private static final long SCAN_PERIOD = 10000;@Overridepublic 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);}@Overrideprotected void onResume() {super.onResume();// Initializes list view adapter.mLeDeviceListAdapter = new LeDeviceListAdapter(this);setListAdapter(mLeDeviceListAdapter);scanLeDevice(true);}@Overrideprotected void onPause() {super.onPause();scanLeDevice(false);mLeDeviceListAdapter.clear();mBLE.disconnect();}@Overrideprotected void onStop() {super.onStop();mBLE.close();}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);if (device == null) return;if (mScanning) {mBluetoothAdapter.stopLeScan(mLeScanCallback);mScanning = false;}mBLE.connect(device.getAddress());}private void scanLeDevice(final boolean enable) {if (enable) {// Stops scanning after a pre-defined scan period.mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);invalidateOptionsMenu();}}, SCAN_PERIOD);mScanning = true;mBluetoothAdapter.startLeScan(mLeScanCallback);} else {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);}invalidateOptionsMenu();}/*** 搜索到BLE终端服务的事件*/private BluetoothLeClass.OnServiceDiscoverListener mOnServiceDiscover = new OnServiceDiscoverListener(){@Overridepublic void onServiceDiscover(BluetoothGatt gatt) {displayGattServices(mBLE.getSupportedGattServices());}};/*** 收到BLE终端数据交互的事件*/private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){/*** BLE终端数据被读的事件*/@Overridepublic 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终端写入数据回调*/@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()+" write "+characteristic.getUuid().toString()+" -> "+new String(characteristic.getValue()));}};// Device scan callback.private BluetoothAdapter.LeScanCallback mLeScanCallback =new BluetoothAdapter.LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {runOnUiThread(new Runnable() {@Overridepublic void run() {mLeDeviceListAdapter.addDevice(device);mLeDeviceListAdapter.notifyDataSetChanged();}});}};private void displayGattServices(List<BluetoothGattService> gattServices) {if (gattServices == null) return;for (BluetoothGattService gattService : gattServices) {//—–Service的字段信息—–//int type = gattService.getType();Log.e(TAG,"–>service type:"+Utils.getServiceType(type));Log.e(TAG,"–>includedServices size:"+gattService.getIncludedServices().size());Log.e(TAG,"–>service uuid:"+gattService.getUuid());//—–Characteristics的字段信息—–//List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();for (final BluetoothGattCharacteristic gattCharacteristic: gattCharacteristics) {Log.e(TAG,"—->char uuid:"+gattCharacteristic.getUuid());int permission = gattCharacteristic.getPermissions();Log.e(TAG,"—->char permission:"+Utils.getCharPermission(permission));int property = gattCharacteristic.getProperties();Log.e(TAG,"—->char property:"+Utils.getCharPropertie(property));byte[] data = gattCharacteristic.getValue();if (data != null && data.length > 0) {Log.e(TAG,"—->char value:"+new String(data));}//UUID_KEY_DATA是可以跟蓝牙模块串口通信的Characteristicif(gattCharacteristic.getUuid().toString().equals(UUID_KEY_DATA)){//测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mBLE.readCharacteristic(gattCharacteristic);}}, 500);//接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()mBLE.setCharacteristicNotification(gattCharacteristic, true);//设置数据内容gattCharacteristic.setValue("send data->");//往蓝牙模块写入数据mBLE.writeCharacteristic(gattCharacteristic);}//—–Descriptors的字段信息—–//List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {Log.e(TAG, "——–>desc uuid:" + gattDescriptor.getUuid());int descPermission = gattDescriptor.getPermissions();Log.e(TAG,"——–>desc permission:"+ Utils.getDescPermission(descPermission));byte[] desData = gattDescriptor.getValue();if (desData != null && desData.length > 0) {Log.e(TAG, "——–>desc value:"+ new String(desData));}}}}//}}

,没有什么可留恋,只有抑制不住的梦想,

Android BLE开发之Android手机与BLE终端通信

相关文章:

你感兴趣的文章:

标签云: