Esempio n. 1
0
    /**
     * Waits for completed requests. Once the first request has been taken, the method will wait
     * WAIT_TIMEOUT ms longer to collect more completed requests.
     *
     * @return Collected feeds or null if the method has been interrupted during the first waiting
     *     period.
     */
    private List<Feed> collectCompletedRequests() {
      List<Feed> results = new LinkedList<Feed>();
      DownloadRequester requester = DownloadRequester.getInstance();
      int tasks = 0;

      try {
        DownloadRequest request = completedRequests.take();
        parserService.submit(new FeedParserTask(request));
        tasks++;
      } catch (InterruptedException e) {
        return null;
      }

      tasks += pollCompletedDownloads();

      isCollectingRequests = true;

      if (requester.isDownloadingFeeds()) {
        // wait for completion of more downloads
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        while (requester.isDownloadingFeeds() && (currentTime - startTime) < WAIT_TIMEOUT) {
          try {
            if (BuildConfig.DEBUG)
              Log.d(TAG, "Waiting for " + (startTime + WAIT_TIMEOUT - currentTime) + " ms");
            sleep(startTime + WAIT_TIMEOUT - currentTime);
          } catch (InterruptedException e) {
            if (BuildConfig.DEBUG) Log.d(TAG, "interrupted while waiting for more downloads");
            tasks += pollCompletedDownloads();
          } finally {
            currentTime = System.currentTimeMillis();
          }
        }

        tasks += pollCompletedDownloads();
      }

      isCollectingRequests = false;

      for (int i = 0; i < tasks; i++) {
        try {
          Feed f = parserService.take().get();
          if (f != null) {
            results.add(f);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();

        } catch (ExecutionException e) {
          e.printStackTrace();
        }
      }

      return results;
    }
Esempio n. 2
0
  private void onDownloadQueued(Intent intent) {
    if (BuildConfig.DEBUG) Log.d(TAG, "Received enqueue request");
    DownloadRequest request = intent.getParcelableExtra(EXTRA_REQUEST);
    if (request == null) {
      throw new IllegalArgumentException("ACTION_ENQUEUE_DOWNLOAD intent needs request extra");
    }

    Downloader downloader = getDownloader(request);
    if (downloader != null) {
      numberOfDownloads.incrementAndGet();
      downloads.add(downloader);
      downloadExecutor.submit(downloader);
      sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED));
    }

    queryDownloads();
  }
Esempio n. 3
0
 /**
  * Adds a new DownloadStatus object to the list of completed downloads and saves it in the
  * database
  *
  * @param status the download that is going to be saved
  */
 private void saveDownloadStatus(DownloadStatus status) {
   completedDownloads.add(status);
   DBWriter.addDownloadStatus(this, status);
 }