@Override
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public void onShowAdvanced() {
    if (selectDownloadFolderFragment != null) selectDownloadFolderFragment.dismiss();

    Intent selectFolderIntent;
    // Create intent depending on system version
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      // Use the system UI for folder selection on Android 5.0 and later
      selectFolderIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    else {
      // Use old custom UI on older Android versions
      selectFolderIntent = new Intent(this, SelectFileActivity.class);
      selectFolderIntent.putExtra(
          SelectFileActivity.SELECTION_MODE_KEY, SelectFileActivity.SelectionMode.FOLDER);
      selectFolderIntent.putExtra(
          SelectFileActivity.INITIAL_PATH_KEY,
          getPreferences(MODE_PRIVATE)
              .getString(
                  SettingsActivity.KEY_DOWNLOAD_FOLDER,
                  EpisodeDownloadManager.getDefaultDownloadFolder().getAbsolutePath()));
    }

    // Start activity. Result will be caught below and pushed down to the SettingsActivity.
    startActivityForResult(selectFolderIntent, DownloadFolderPreference.REQUEST_CODE);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
      selectDownloadFolderFragment = new SelectDownloadFolderFragment();
      selectDownloadFolderFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppDialog);

      // Make sure we have the permission needed
      if (!Podcatcher.canWriteExternalStorage())
        requestPermissions(new String[] {WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_REQUEST_CODE);
      else selectDownloadFolderFragment.show(getFragmentManager(), SELECT_FOLDER_DIALOG_TAG);
    } else
      this.selectDownloadFolderFragment =
          (SelectDownloadFolderFragment)
              getFragmentManager().findFragmentByTag(SELECT_FOLDER_DIALOG_TAG);
  }
  @Override
  public void onSelectFolder(String path) {
    if (selectDownloadFolderFragment != null) selectDownloadFolderFragment.dismiss();

    Intent result = new Intent();
    result.setData(Uri.fromFile(new File(path)));

    setResult(RESULT_OK, result);
    finish();
  }
 @Override
 public void onRequestPermissionsResult(
     int requestCode, String[] permissions, int[] grantResults) {
   switch (requestCode) {
     case STORAGE_PERMISSION_REQUEST_CODE:
       if (grantResults.length > 0
           && grantResults[0] == PackageManager.PERMISSION_GRANTED
           && selectDownloadFolderFragment != null)
         selectDownloadFolderFragment.show(getFragmentManager(), SELECT_FOLDER_DIALOG_TAG);
       else {
         showToast(getString(R.string.file_select_access_denied));
         onCancel(null);
       }
   }
 }