SHARE
TWEET

[libaums]: UsbWriteOperation class

kuza2010 Jan 21st, 2020 (edited) 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. protected void doWrite() throws IOException {
  2.     if (this.state.compareAndSet(State.NEW, State.RUNNING)) {
  3.         // some checks before write and create Output Stream
  4.         if (!prepareForWrite()) {
  5.             return;
  6.         }
  7.     }
  8.     if ((this.state.get() == State.RUNNING)
  9.             || this.state.compareAndSet(State.SUSPENDED, State.RUNNING)) {
  10.         byte[] nextByte;
  11.         try {
  12.             // Integer.maxValue
  13.             int executeCount = weight;
  14.             do {
  15.                 // retrieves next block of data from queue
  16.                 nextByte = blockingQueue.poll();
  17.                 if (nextByte == null) {
  18.                     //suspend because blocking queue is empty
  19.                     suspend();
  20.                     break;
  21.                 }
  22.                 if (isPoissonPill(nextByte)) {
  23.                     state.set(State.COMPLETED);
  24.                     Timber.tag(TAG).i("Write completed for the file %s", destFile.getPath());
  25.                     break;
  26.                 } else {
  27.                     // write data to device
  28.                     outputStream.write(nextByte);
  29.                     publishProgress(nextByte.length);
  30.                     executeCount--;
  31.                 }
  32.             } while (isExitCondition(executeCount));
  33.             state.compareAndSet(State.RUNNING, State.SUSPENDED);
  34.         } finally {
  35.             if (State.COMPLETED == state.get()) {
  36.                 closeStreams();
  37.                 delegate.onWriteSuccess();
  38.             }
  39.         }
  40.     }
  41. }
  42.  
  43. // check EOF
  44. private boolean isPoissonPill(byte[] nextByte) {
  45.     return nextByte == Constants.EOF;
  46. }
  47.  
  48. void createStream() throws USBException, IOException {
  49.     // FileSystemService.getOutputStream will be called
  50.     outputStream = api.getFileSystemService().getOutputStream(usbDevice, destFile);
  51.     file = api.getFileSystemService().getUsbFile(usbDevice, destFile);
  52. }
  53.  
  54. private void closeStreams() {
  55.     try {
  56.         if (outputStream != null) {
  57.             outputStream.close();
  58.             outputStream = null;
  59.         }
  60.     } catch (IOException e) {
  61.         e.printStackTrace();
  62.     }
  63. }
  64.  
  65. @Override
  66. public boolean suspend() {
  67.     return this.state.compareAndSet(State.RUNNING, State.SUSPENDED);
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top