Example usage for android.os Environment DIRECTORY_DOWNLOADS

List of usage examples for android.os Environment DIRECTORY_DOWNLOADS

Introduction

In this page you can find the example usage for android.os Environment DIRECTORY_DOWNLOADS.

Prototype

String DIRECTORY_DOWNLOADS

To view the source code for android.os Environment DIRECTORY_DOWNLOADS.

Click Source Link

Document

Standard directory in which to place files that have been downloaded by the user.

Usage

From source file:com.github.se_bastiaan.torrentstreamerserver.sample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    videoLocationText = (TextView) findViewById(R.id.video_location_text);
    button = (Button) findViewById(R.id.button);
    progressBar = (ProgressBar) findViewById(R.id.progress);

    String action = getIntent().getAction();
    Uri data = getIntent().getData();// w  w  w.j  a v a 2s  .c o m
    if (action != null && action.equals(Intent.ACTION_VIEW) && data != null) {
        try {
            streamUrl = URLDecoder.decode(data.toString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    TorrentOptions torrentOptions = new TorrentOptions.Builder()
            .saveLocation(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
            .removeFilesAfterStop(true).build();

    String ipAddress = "127.0.0.1";
    try {
        InetAddress inetAddress = getIpAddress(this);
        if (inetAddress != null) {
            ipAddress = inetAddress.getHostAddress();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    torrentStreamServer = TorrentStreamServer.getInstance();
    torrentStreamServer.setTorrentOptions(torrentOptions);
    torrentStreamServer.setServerHost(ipAddress);
    torrentStreamServer.setServerPort(8080);
    torrentStreamServer.startTorrentStream();
    torrentStreamServer.addListener(this);

    button.setOnClickListener(onClickListener);

    progressBar.setMax(100);
}

From source file:com.android.xbrowser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    if (httpHost != null) {
        ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    }/* ww  w  .j a va2s.c  o m*/
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:com.esri.squadleader.controller.AdvancedSymbolController.java

/**
 * Copies the MIL-STD-2525C symbol dictionary from assets to the device's downloads directory if
 * it is not already there.//from w w w  .  j a  v  a 2 s.  c o m
 *
 * @param assetManager            the application's AssetManager, from which the advanced symbology database
 *                                will be copied.
 * @param symbolDictionaryDirname the name of the asset directory that contains the advanced symbology
 *                                database.
 * @return the symbol dictionary directory. This may be freshly copied or it might have already
 * been there.
 * @throws IOException if the symbol dictionary cannot be copied to disk.
 */
public static File copySymbolDictionaryToDisk(AssetManager assetManager, String symbolDictionaryDirname)
        throws IOException {
    File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (!downloadsDir.exists()) {
        downloadsDir.mkdirs();
    }
    File symDictDir = new File(downloadsDir, symbolDictionaryDirname);

    boolean copyNeeded = !symDictDir.exists();
    if (!copyNeeded) {
        /**
         * Check to see if we need to upgrade the symbol dictionary. One way is to
         * see if PositionReport.json's renderer is of type 2525C (10.2) or mil2525c (10.2.4).
         */
        StringBuilder sb = new StringBuilder();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(new File(symDictDir, "messagetypes/PositionReport.json")));
            String line;
            while (null != (line = in.readLine())) {
                sb.append(line);
            }
            JSONObject json = new JSONObject(sb.toString());
            if (!"mil2525c".equals(json.getJSONObject("renderer").getString("dictionaryType"))) {
                copyNeeded = true;
            }
        } catch (Exception e) {
            copyNeeded = true;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Throwable t) {
                    //Swallow
                }
            }
        }
    }
    if (copyNeeded) {
        symDictDir.delete();
        Utilities.copyAssetToDir(assetManager, symbolDictionaryDirname, downloadsDir.getAbsolutePath());
    }
    return symDictDir;
}

From source file:com.tcity.android.ui.info.BuildArtifactsFragment.java

@Override
public void onDownloadClick(@NotNull BuildArtifact artifact) {
    //noinspection ResultOfMethodCallIgnored
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();

    DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(calculateArtifactRequest(artifact));
}

From source file:org.jraf.android.downloadandshareimage.app.downloadandshare.DownloadAndShareActivity.java

public File getTemporaryFile() throws IOException {
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    dir.mkdirs();//from   w w w  .  j a v  a 2 s  .co  m
    String fileName = FileUtil.getValidFileName(mUrl);
    fileName = fileName.substring(0, Math.min(80, fileName.length()));
    File file = new File(dir, fileName);
    Log.d("file=" + file);
    if (file.exists())
        file.delete();
    return file;
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void BackupDatabase() {
    String loc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            + "/AndroidLocalTodoBackup.db";
    try {//from  ww  w. j  a v a 2s  .c o m
        mDB.BackupDatabase(loc);
        String[] paths = { loc };
        MediaScannerConnection.scanFile(this, paths, null, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskListActivity.this);
        AlertDialog dlg = builder.setTitle("Success!").setMessage("Database backed up!").create();
        dlg.show();
    } catch (java.io.IOException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskListActivity.this);
        AlertDialog dlg = builder.setTitle("File I/O error!").setMessage(e.getMessage()).create();
        dlg.show();
    }
}

From source file:org.glucosio.android.presenter.ExportPresenter.java

private boolean dirExists() {
    final File file = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/glucosio");
    return file.exists() || file.mkdirs();
}

From source file:com.mogoweb.browser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    //        HttpHost httpHost;
    //        try {
    //            httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    //            if (httpHost != null) {
    //                ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    //            }
    //        } catch (IllegalArgumentException ex) {
    //            Log.e(LOGTAG,"Download failed: " + ex);
    //            client.close();
    //            return;
    //        }/* w ww.j  ava  2s .  c  o m*/
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mimeType = newMimeType;
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:com.geekandroid.sdk.sample.crop.ResultActivity.java

private void copyFileToDownloads(Uri croppedFileUri) throws Exception {
    String downloadsDirectoryPath = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(),
            croppedFileUri.getLastPathSegment());

    File saveFile = new File(downloadsDirectoryPath, filename);

    FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath()));
    FileOutputStream outStream = new FileOutputStream(saveFile);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();/*from  w  w w.ja  v  a  2 s.  c  om*/
    outStream.close();

    showNotification(saveFile);
}

From source file:de.baumann.browser.popups.Popup_files.java

private void setFilesList() {

    deleteDatabase("files_DB_v01.db");

    File f = new File(sharedPref.getString("files_startFolder",
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()));
    final File[] files = f.listFiles();

    Arrays.sort(files, new Comparator<File>() {
        @Override//from  w ww  .  java 2  s . c  o m
        public int compare(File file1, File file2) {
            if (file1.isDirectory()) {
                if (file2.isDirectory()) {
                    return String.valueOf(file1.getName().toLowerCase())
                            .compareTo(file2.getName().toLowerCase());
                } else {
                    return -1;
                }
            } else {
                if (file2.isDirectory()) {
                    return 1;
                } else {
                    return String.valueOf(file1.getName().toLowerCase())
                            .compareTo(file2.getName().toLowerCase());
                }
            }
        }
    });

    // looping through all items <item>
    if (files.length == 0) {
        Snackbar.make(listView, R.string.toast_files, Snackbar.LENGTH_LONG).show();
    }

    for (File file : files) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        String file_Name = file.getName().substring(0, 1).toUpperCase() + file.getName().substring(1);
        String file_Size = getReadableFileSize(file.length());
        String file_date = formatter.format(new Date(file.lastModified()));
        String file_path = file.getAbsolutePath();

        String file_ext;
        if (file.isDirectory()) {
            file_ext = ".";
        } else {
            file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("."));
        }

        db.open();
        if (db.isExist(file_Name)) {
            Log.i(TAG, "Entry exists" + file_Name);
        } else {
            db.insert(file_Name, file_Size, file_ext, file_path, file_date);
        }
    }

    try {
        db.insert("...", "", "", "", "");
    } catch (Exception e) {
        Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
    }

    //display data
    final int layoutstyle = R.layout.list_item;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "files_title", "files_content", "files_creation" };
    final Cursor row = db.fetchAllData(this);
    adapter = new SimpleCursorAdapter(this, layoutstyle, row, column, xml_id, 0) {
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row2 = (Cursor) listView.getItemAtPosition(position);
            final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon"));
            final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));
            final File pathFile = new File(files_attachment);

            View v = super.getView(position, convertView, parent);
            final ImageView iv = (ImageView) v.findViewById(R.id.icon_notes);

            iv.setVisibility(View.VISIBLE);

            if (pathFile.isDirectory()) {
                iv.setImageResource(R.drawable.folder);
            } else {
                switch (files_icon) {
                case "":
                    iv.setImageResource(R.drawable.arrow_up_dark);
                    break;
                case ".m3u8":
                case ".mp3":
                case ".wma":
                case ".midi":
                case ".wav":
                case ".aac":
                case ".aif":
                case ".amp3":
                case ".weba":
                case ".ogg":
                    iv.setImageResource(R.drawable.file_music);
                    break;
                case ".mpeg":
                case ".mp4":
                case ".webm":
                case ".qt":
                case ".3gp":
                case ".3g2":
                case ".avi":
                case ".f4v":
                case ".flv":
                case ".h261":
                case ".h263":
                case ".h264":
                case ".asf":
                case ".wmv":
                    try {
                        Glide.with(Popup_files.this).load(files_attachment) // or URI/path
                                .override(76, 76).centerCrop().into(iv); //imageView to set thumbnail to
                    } catch (Exception e) {
                        Log.w("HHS_Moodle", "Error load thumbnail", e);
                        iv.setImageResource(R.drawable.file_video);
                    }
                    break;
                case ".vcs":
                case ".vcf":
                case ".css":
                case ".ics":
                case ".conf":
                case ".config":
                case ".java":
                case ".html":
                    iv.setImageResource(R.drawable.file_xml);
                    break;
                case ".apk":
                    iv.setImageResource(R.drawable.android);
                    break;
                case ".pdf":
                    iv.setImageResource(R.drawable.file_pdf);
                    break;
                case ".rtf":
                case ".csv":
                case ".txt":
                case ".doc":
                case ".xls":
                case ".ppt":
                case ".docx":
                case ".pptx":
                case ".xlsx":
                case ".odt":
                case ".ods":
                case ".odp":
                    iv.setImageResource(R.drawable.file_document);
                    break;
                case ".zip":
                case ".rar":
                    iv.setImageResource(R.drawable.zip_box);
                    break;
                case ".gif":
                case ".bmp":
                case ".tiff":
                case ".svg":
                case ".png":
                case ".jpg":
                case ".JPG":
                case ".jpeg":
                    try {
                        Glide.with(Popup_files.this).load(files_attachment) // or URI/path
                                .diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true)
                                .override(76, 76).centerCrop().into(iv); //imageView to set thumbnail to
                    } catch (Exception e) {
                        Log.w("HHS_Moodle", "Error load thumbnail", e);
                        iv.setImageResource(R.drawable.file_image);
                    }
                    break;
                default:
                    iv.setImageResource(R.drawable.file);
                    break;
                }
            }

            if (files_attachment.isEmpty()) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        iv.setImageResource(R.drawable.arrow_up_dark);
                    }
                }, 350);
            }

            return v;
        }
    };

    //display data by filter
    final String note_search = sharedPref.getString("filter_filesBY", "files_title");
    sharedPref.edit().putString("filter_filesBY", "files_title").apply();
    editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    listView.setAdapter(adapter);
    //onClick function
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            Cursor row2 = (Cursor) listView.getItemAtPosition(position);
            final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon"));
            final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));

            final File pathFile = new File(files_attachment);

            if (pathFile.isDirectory()) {
                try {
                    sharedPref.edit().putString("files_startFolder", files_attachment).apply();
                    setFilesList();
                } catch (Exception e) {
                    Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
                }
            } else if (files_attachment.equals("")) {
                try {
                    final File pathActual = new File(sharedPref.getString("files_startFolder",
                            Environment.getExternalStorageDirectory().getPath()));
                    sharedPref.edit().putString("files_startFolder", pathActual.getParent()).apply();
                    setFilesList();
                } catch (Exception e) {
                    Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
                }
            } else {
                helper_main.open(files_icon, Popup_files.this, pathFile, listView);
            }
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor row2 = (Cursor) listView.getItemAtPosition(position);
            final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title"));
            final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));

            final File pathFile = new File(files_attachment);

            if (pathFile.isDirectory()) {
                Snackbar snackbar = Snackbar
                        .make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                sharedPref.edit().putString("files_startFolder", pathFile.getParent()).apply();
                                deleteRecursive(pathFile);
                                setFilesList();
                            }
                        });
                snackbar.show();

            } else {
                final CharSequence[] options = { getString(R.string.choose_menu_2),
                        getString(R.string.choose_menu_3), getString(R.string.choose_menu_4) };

                final AlertDialog.Builder dialog = new AlertDialog.Builder(Popup_files.this);
                dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
                dialog.setItems(options, new DialogInterface.OnClickListener() {
                    @SuppressWarnings("ResultOfMethodCallIgnored")
                    @Override
                    public void onClick(DialogInterface dialog, int item) {

                        if (options[item].equals(getString(R.string.choose_menu_2))) {

                            if (pathFile.exists()) {
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("image/png");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, files_title);
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, files_title);
                                Uri bmpUri = Uri.fromFile(pathFile);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.app_share_file))));
                            }
                        }
                        if (options[item].equals(getString(R.string.choose_menu_4))) {

                            Snackbar snackbar = Snackbar
                                    .make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
                                    .setAction(R.string.toast_yes, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            pathFile.delete();
                                            setFilesList();
                                        }
                                    });
                            snackbar.show();
                        }
                        if (options[item].equals(getString(R.string.choose_menu_3))) {
                            sharedPref.edit().putString("pathFile", files_attachment).apply();
                            editText.setVisibility(View.VISIBLE);
                            helper_editText.showKeyboard(Popup_files.this, editText, 2, files_title,
                                    getString(R.string.bookmark_edit_title));
                        }
                    }
                });
                dialog.show();
            }

            return true;
        }
    });
}