标签:特定 aik address invoke data ecif util zed red
三、安卓中GATT的操作
和经典蓝牙最开始一样,要检测蓝牙是否可用和蓝牙是否打开,这部分代码就不贴出来了。
一般操作GATT的教程都把操作放在安卓的server里面,具体原因还请大神指教。下面的server代码可以直接当作操作GATT的模板来使用,大部分都是些回调函数和对服务、特征值进行操作的方法:
public class UartService extends Service { private final static String TAG = UartService.class.getSimpleName(); List<BluetoothGattService> serviceList = new ArrayList<BluetoothGattService>();//发现的服务列表 private BluetoothAdapter mBluetoothAdapter;//本地蓝牙适配器 private String mBluetoothDeviceAddress;//本地蓝牙MAC地址 private BluetoothGatt mBluetoothGatt;//GTAA /** * 假设生产商提供了一个服务,该服务里面有两个特征值 */ private BluetoothGattService mBluetoothGattService;//gatt服务 private BluetoothGattCharacteristic mBluetoothGattCharacteristic1;//gatt特征值1 private BluetoothGattCharacteristic mBluetoothGattCharacteristic2;//gatt特征值2 private int mConnectionState = STATE_DISCONNECTED; //连接状态常量 private static final int STATE_DISCONNECTED = 0; private static final int STATE_CONNECTING = 1; private static final int STATE_CONNECTED = 2; //蓝牙厂商提供的UUID private static final UUID UUID_SERVICE = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"); //服务 private static final UUID UUID_CHARA1 = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"); //特征值1 private static final UUID UUID_CHARA2 = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb"); //特征值2 // Implements callback methods for GATT events that the app cares about. For example, // connection change and services discovered. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { mConnectionState = STATE_CONNECTED; Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { mConnectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) {//服务被发现 if (status == BluetoothGatt.GATT_SUCCESS) { System.out.println("Service has bean discover."); mBluetoothGattService = gatt.getService(UUID_SERVICE);//发现服务 } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Utiles.setData(characteristic); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { } }; public class LocalBinder extends Binder { UartService getService() { return UartService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { // After using a given device, you should make sure that BluetoothGatt.close() is called // such that resources are cleaned up properly. In this particular example, close() is // invoked when the UI is disconnected from the Service. close(); return super.onUnbind(intent); } private final IBinder mBinder = new LocalBinder(); /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() {//初始化 // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } return true; } /** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) {//连接服务 if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; } /** * Disconnects an existing connection or cancel a pending connection. The disconnection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public void disconnect() { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.disconnect(); } /** * After using a given BLE device, the app must call this method to ensure resources are * released properly. */ public void close() { if (mBluetoothGatt == null) { return; } mBluetoothGatt.close(); mBluetoothGatt = null; } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.readCharacteristic(characteristic); } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void writeCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.writeCharacteristic(characteristic); } public boolean writeCharacteristic1Info(String s){ if(mBluetoothGattService==null){ return false; } mBluetoothGattCharacteristic1 = mBluetoothGattService.getCharacteristic(UUID_CHARA1);//获得特征值1 mBluetoothGattCharacteristic1.setValue(s.getBytes()); writeCharacteristic(mBluetoothGattCharacteristic1); return true; } /** * Enables or disables notification on a give characteristic. * * @param characteristic Characteristic to act on. * @param enabled If true, enable notification. False otherwise. */ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); } /** * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully. * * @return A {@code List} of supported services. */ public List<BluetoothGattService> getSupportedGattServices() { if (mBluetoothGatt == null) return null; return mBluetoothGatt.getServices(); } @Override//使用startService启动服务时回调 public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("UartService Start"); return super.onStartCommand(intent, flags, startId); } }
ps:在发现服务后,最好把特征值取出来成一个列表,然后使用 setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled)方法对所有特征值进行设置,确保服务的特征值都可读可写。
mBluetoothGattService = gatt.getService(UUID_SERVICE);//发现服务 List<BluetoothGattCharacteristic> characteristics = mBluetoothGattService.getCharacteristics(); if(characteristics.size()!=2){return;}//如果此服务不是有2个特征值,说明不是我们要的服务 for (BluetoothGattCharacteristic bluetoothGattCharacteristic : characteristics) { setCharacteristicNotification(bluetoothGattCharacteristic, true); } mBluetoothGattCharacteristic1 = characteristics.get(0); mBluetoothGattCharacteristic2 = characteristics.get(1);
写完Service之后就可以用Service了
四、Service的使用
mUartService.initialize();//初始化本地设备
mUartService.connect(String MacAddress);//通过远程设备地址链接到远程设备
writeCharacteristic1Info(String s);
总结
标签:特定 aik address invoke data ecif util zed red
原文地址:http://www.cnblogs.com/sovagxa/p/7810204.html