public void start() { Log.i(TAG, "download start"); if (mDownloadThread != null) { mDownloadThread.isRunning = false; try { mDownloadThread.interrupt(); } catch (Exception e) { e.printStackTrace(); } } mDownloadThread = new DownloadThread(); downloadingPosition = -1; isDownloaded = new boolean[book.pageCount]; for (int i = 0; i < book.pageCount; i++) { isDownloaded[i] = PageApi.isPageOriginImageLocalFileExist(context, book, i + 1); } state = STATE_START; mDownloadThread.start(); }
@Override public void run() { Log.i(TAG, "download thread start"); if (listener != null) listener.onStateChange(STATE_START); while (isRunning && !isAllDownloaded()) { downloadingPosition = nextToDownloadPosition(); Log.i(TAG, "downloadingPosition:" + downloadingPosition); if (state == STATE_PAUSE) { Log.i(TAG, "download paused"); if (listener != null) listener.onStateChange(STATE_PAUSE); while (state == STATE_PAUSE) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } if (state == STATE_STOP) { Log.i(TAG, "download stopped"); if (listener != null) listener.onStateChange(STATE_STOP); isRunning = false; return; } File tempFile = null; try { tempFile = PageApi.getPageOriginImageFile(context, book, downloadingPosition + 1); } catch (Exception e) { e.printStackTrace(); } if (tempFile != null) { Log.i(TAG, "download finish"); isDownloaded[downloadingPosition] = true; if (listener != null) listener.onFinish(currentPosition); } else { Log.i(TAG, "download error"); if (listener != null) listener.onError(currentPosition, -1); } } Log.i(TAG, "all downloaded"); if (listener != null) listener.onStateChange(STATE_ALL_OK); isRunning = false; }