Считать данные из файла, используя
protected byte[] readFile(File file) {
BufferedInputStream buf;
int size = (int) file.length();
byte[] mDataFile = new byte[size];
//mDataFile = new byte[size];
try {
buf = new BufferedInputStream(new FileInputStream(file));
buf.read(mDataFile, 0, size);
} catch (IOException e) {
e.printStackTrace();
}
return mDataFile;
}
Затем запустите сканирование устройства. После подключения устройства с использованием определенного macAddress
вызовите метод connectToDevice
public static BluetoothGatt connectToDevice(Context context,
BluetoothDevice device,
BluetoothGattCallback mGattCallBack){
BluetoothGatt connectedGatt = null;
if (device != null) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
connectedGatt = device.connectGatt(context, false,
mGattCallBack,
BluetoothDevice.DEVICE_TYPE_LE,
BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M);
}else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
connectedGatt = device.connectGatt(context, false, mGattCallBack, BluetoothDevice.DEVICE_TYPE_LE);
} else if (android.os.Build.VERSION.SDK_INT >= 21) {
connectedGatt = connectGattApi21(context, device, mGattCallBack);
} else {
connectedGatt = device.connectGatt(context, false,
mGattCallBack);
}
} else {
//WiSeSdkFileWritter.writeToFile(fileName, TAG + " FAILED could not find remote device/ remote device is null >>" + macAddress);
}
return connectedGatt;
}
затем обрабатывают методы обратного вызова BluetoothGattCallback - onServicesDiscovered, onCharacteristicWrite, onConnectionStateChange
В методе onServicesDiscovered вы получите BluetoothGattService. Из gattService извлеките характеристики. наконец, запишите характеристики устройства ble.
BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
BluetoothGattService mService = gatt.getService(service);
mCharacteristics = mService.getCharacteristic(characteristics);
mCharacteristics.setValue(bytes);
Logger.v(TAG, "data write count ::" + writeCounter++);
Timer t = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
gatt.writeCharacteristic(mCharacteristics);
}
};
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
}
};