Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protected void doWrite() throws IOException {
- if (this.state.compareAndSet(State.NEW, State.RUNNING)) {
- // some checks before write and create Output Stream
- if (!prepareForWrite()) {
- return;
- }
- }
- if ((this.state.get() == State.RUNNING)
- || this.state.compareAndSet(State.SUSPENDED, State.RUNNING)) {
- byte[] nextByte;
- try {
- // Integer.maxValue
- int executeCount = weight;
- do {
- // retrieves next block of data from queue
- nextByte = blockingQueue.poll();
- if (nextByte == null) {
- //suspend because blocking queue is empty
- suspend();
- break;
- }
- if (isPoissonPill(nextByte)) {
- state.set(State.COMPLETED);
- Timber.tag(TAG).i("Write completed for the file %s", destFile.getPath());
- break;
- } else {
- // write data to device
- outputStream.write(nextByte);
- publishProgress(nextByte.length);
- executeCount--;
- }
- } while (isExitCondition(executeCount));
- state.compareAndSet(State.RUNNING, State.SUSPENDED);
- } finally {
- if (State.COMPLETED == state.get()) {
- closeStreams();
- delegate.onWriteSuccess();
- }
- }
- }
- }
- // check EOF
- private boolean isPoissonPill(byte[] nextByte) {
- return nextByte == Constants.EOF;
- }
- void createStream() throws USBException, IOException {
- // FileSystemService.getOutputStream will be called
- outputStream = api.getFileSystemService().getOutputStream(usbDevice, destFile);
- file = api.getFileSystemService().getUsbFile(usbDevice, destFile);
- }
- private void closeStreams() {
- try {
- if (outputStream != null) {
- outputStream.close();
- outputStream = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public boolean suspend() {
- return this.state.compareAndSet(State.RUNNING, State.SUSPENDED);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement