private void handleKeyEvent(KeyEvent event) {
    if (event.getAction() != KeyEvent.ACTION_DOWN || event.getRepeatCount() > 0) {
      return;
    }

    switch (event.getKeyCode()) {
      case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
      case KeyEvent.KEYCODE_HEADSETHOOK:
        downloadService.togglePlayPause();
        break;
      case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
        downloadService.previous();
        break;
      case KeyEvent.KEYCODE_MEDIA_NEXT:
        if (downloadService.getCurrentPlayingIndex() < downloadService.size() - 1) {
          downloadService.next();
        }
        break;
      case KeyEvent.KEYCODE_MEDIA_STOP:
        downloadService.reset();
        break;
      case KeyEvent.KEYCODE_MEDIA_PLAY:
        downloadService.play();
        break;
      case KeyEvent.KEYCODE_MEDIA_PAUSE:
        downloadService.pause();
        break;
      default:
        break;
    }
  }
  @Override
  public void setJukeboxEnabled(boolean jukeboxEnabled) {
    this.jukeboxEnabled = jukeboxEnabled;
    jukeboxService.setEnabled(jukeboxEnabled);
    if (jukeboxEnabled) {
      reset();

      // Cancel current download, if necessary.
      if (currentDownloading != null) {
        currentDownloading.cancelDownload();
      }
    }
  }
 @Override
 public synchronized void clearIncomplete() {
   reset();
   Iterator<DownloadFile> iterator = downloadList.iterator();
   while (iterator.hasNext()) {
     DownloadFile downloadFile = iterator.next();
     if (!downloadFile.isCompleteFileAvailable()) {
       iterator.remove();
     }
   }
   lifecycleSupport.serializeDownloadQueue();
   updateJukeboxPlaylist();
 }
 @Override
 public synchronized void remove(DownloadFile downloadFile) {
   if (downloadFile == currentDownloading) {
     currentDownloading.cancelDownload();
     currentDownloading = null;
   }
   if (downloadFile == currentPlaying) {
     reset();
     setCurrentPlaying(null);
   }
   downloadList.remove(downloadFile);
   revision++;
   lifecycleSupport.serializeDownloadQueue();
   updateJukeboxPlaylist();
 }
  public synchronized void clear(boolean serialize) {
    reset();
    downloadList.clear();
    revision++;
    if (currentDownloading != null) {
      currentDownloading.cancelDownload();
      currentDownloading = null;
    }
    setCurrentPlaying(null);

    if (serialize) {
      lifecycleSupport.serializeDownloadQueue();
    }
    updateJukeboxPlaylist();
  }
 private synchronized void play(int index, boolean start) {
   if (index < 0 || index >= size()) {
     reset();
     setCurrentPlaying(null);
   } else {
     setCurrentPlaying(index);
     checkDownloads();
     if (start) {
       if (jukeboxEnabled) {
         jukeboxService.skip(getCurrentPlayingIndex(), 0);
         setPlayerState(STARTED);
       } else {
         bufferAndPlay();
       }
     }
   }
 }
  private synchronized void bufferAndPlay() {
    reset();

    bufferTask = new BufferTask(currentPlaying, 0);
    bufferTask.start();
  }