我想使用计时器进行多次写入。我正在尝试执行以下操作:
当我写信时,我想收到响应(OnWriteSuccess),当我收到它时,我会再次写信。
前十到二十次写入还可以,但在那之后,每次写入之间会有 2 到 4 秒的延迟。
boolean envia = true;
public void write() {
Timer myTimer = null;
if (myTimer == null) {
Handler handler = null;
if (handler == null) {
handler = new Handler();
}
myTimer = new Timer();
Handler finalHandler = handler;
myTimer.schedule(new TimerTask() {
@Override
public void run() {
finalHandler.post(new Runnable() {
@Override
public void run() {
if (envia) {
envia = false;
if (buc == 256) {
buc = 0;
}
byte bytesToWrite[] = new byte[20];
for (int x = 0; x < 20; x++) {
bytesToWrite[x] = (byte) buc;
buc++;
}
if (isConnected()) {
connectionObservable
.flatMap(rxBleConnection -> rxBleConnection.writeCharacteristic(UUID_1, bytesToWrite))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
bytes -> onWriteSuccess(),
CharacteristicOperationExampleActivity.this::onWriteFailure
);
}
}
}
});
}
}, 200, 300);
private void onWriteSuccess() {
//noinspection ConstantConditions
Snackbar.make(findViewById(R.id.main), "Write success", Snackbar.LENGTH_SHORT).show();
envia = true;
}