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.ywesee.amiko.MainActivity.java

/**
 * Downloads and updates the SQLite database and the error report file
 *///  www .j  a v a2s  . c o m
public void downloadUpdates() {
    // Signal that update is in progress
    mUpdateInProgress = true;
    mDownloadedFileCount = 0;

    // First check network connection
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    // Fetch data...
    if (networkInfo != null && networkInfo.isConnected()) {
        // File URIs
        Uri databaseUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedDatabase());
        Uri reportUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appReportFile());
        Uri interactionsUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedInteractionsFile());
        // NOTE: the default download destination is a shared volume where the system might delete your file if
        // it needs to reclaim space for system use
        DownloadManager.Request requestDatabase = new DownloadManager.Request(databaseUri);
        DownloadManager.Request requestReport = new DownloadManager.Request(reportUri);
        DownloadManager.Request requestInteractions = new DownloadManager.Request(interactionsUri);
        // Allow download only over WIFI and Mobile network
        requestDatabase.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestReport.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestInteractions.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        // Download visible and shows in notifications while in progress and after completion
        requestDatabase.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestReport.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestInteractions
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // Set the title of this download, to be displayed in notifications (if enabled).
        requestDatabase.setTitle("AmiKo SQLite database update");
        requestReport.setTitle("AmiKo report update");
        requestInteractions.setTitle("AmiKo drug interactions update");
        // Set a description of this download, to be displayed in notifications (if enabled)
        requestDatabase.setDescription("Updating the AmiKo database.");
        requestReport.setDescription("Updating the AmiKo error report.");
        requestInteractions.setDescription("Updating the AmiKo drug interactions.");
        // Set local destination to standard directory (place where files downloaded by the user are placed)
        /*
        String main_expansion_file_path = Utilities.expansionFileDir(getPackageName());
        requestDatabase.setDestinationInExternalPublicDir(main_expansion_file_path, Constants.appZippedDatabase());
        */
        requestDatabase.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedDatabase());
        requestReport.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appReportFile());
        requestInteractions.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedInteractionsFile());
        // Check if file exist on non persistent store. If yes, delete it.
        if (Utilities.isExternalStorageReadable() && Utilities.isExternalStorageWritable()) {
            Utilities.deleteFile(Constants.appZippedDatabase(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appReportFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appZippedInteractionsFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        }
        // The downloadId is unique across the system. It is used to make future calls related to this download.
        mDatabaseId = mDownloadManager.enqueue(requestDatabase);
        mReportId = mDownloadManager.enqueue(requestReport);
        mInteractionsId = mDownloadManager.enqueue(requestInteractions);

        mProgressBar = new ProgressDialog(MainActivity.this);
        mProgressBar.setMessage("Downloading SQLite database...");
        mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressBar.setProgress(0);
        mProgressBar.setMax(100);
        mProgressBar.setCancelable(false);
        mProgressBar.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean downloading = true;
                while (downloading) {
                    DownloadManager.Query q = new DownloadManager.Query();
                    q.setFilterById(mDatabaseId);
                    Cursor cursor = mDownloadManager.query(q);
                    cursor.moveToFirst();
                    int bytes_downloaded = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    if (cursor.getInt(cursor.getColumnIndex(
                            DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        if (mProgressBar.isShowing())
                            mProgressBar.dismiss();
                    }
                    final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setProgress((int) dl_progress);
                        }
                    });
                    cursor.close();
                }
            }
        }).start();
    } else {
        // Display error report
    }
}

From source file:com.f8full.casserolesencours.CasserolesEnCoursActivity.java

private File getSDCardFile(boolean checkWriteAccess) {
    boolean externalStorageAvailable = false;
    boolean externalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        externalStorageAvailable = externalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        externalStorageAvailable = true;
        externalStorageWriteable = false;
    } else {/*from  w ww.  j a  v a2 s .co  m*/
        // Something else is wrong. It may be one of many other states, but all we need
        //  to know is we can neither read nor write
        externalStorageAvailable = externalStorageWriteable = false;
    }

    if (externalStorageAvailable == false)
        return null;
    else if (checkWriteAccess && !externalStorageWriteable)
        return null;
    else
        return getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);

}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private boolean copyPart(PduPart part, String fallback) {
    Uri uri = part.getDataUri();/*from   ww  w  . ja v  a2  s .  c  o  m*/
    String type = new String(part.getContentType());
    boolean isDrm = DrmUtils.isDrmType(type);
    if (isDrm) {
        type = MmsApp.getApplication().getDrmManagerClient().getOriginalMimeType(part.getDataUri());
    }
    if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) && !ContentType.isAudioType(type)) {
        return true; // we only save pictures, videos, and sounds. Skip the text parts,
                     // the app (smil) parts, and other type that we can't handle.
                     // Return true to pretend that we successfully saved the part so
                     // the whole save process will be counted a success.
    }
    InputStream input = null;
    FileOutputStream fout = null;
    try {
        input = mContentResolver.openInputStream(uri);
        if (input instanceof FileInputStream) {
            FileInputStream fin = (FileInputStream) input;

            byte[] location = part.getName();
            if (location == null) {
                location = part.getFilename();
            }
            if (location == null) {
                location = part.getContentLocation();
            }

            String fileName;
            if (location == null) {
                // Use fallback name.
                fileName = fallback;
            } else {
                // For locally captured videos, fileName can end up being something like this:
                //      /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
                fileName = new String(location);
            }
            File originalFile = new File(fileName);
            fileName = originalFile.getName(); // Strip the full path of where the "part" is
                                               // stored down to just the leaf filename.

            // Depending on the location, there may be an
            // extension already on the name or not. If we've got audio, put the attachment
            // in the Ringtones directory.
            String dir = Environment.getExternalStorageDirectory() + "/"
                    + (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES
                            : Environment.DIRECTORY_DOWNLOADS)
                    + "/";
            String extension;
            int index;
            if ((index = fileName.lastIndexOf('.')) == -1) {
                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
            } else {
                extension = fileName.substring(index + 1, fileName.length());
                fileName = fileName.substring(0, index);
            }
            if (isDrm) {
                extension += DrmUtils.getConvertExtension(type);
            }
            // Remove leading periods. The gallery ignores files starting with a period.
            fileName = fileName.replaceAll("^.", "");

            File file = getUniqueDestination(dir + fileName, extension);

            // make sure the path is valid and directories created for this file.
            File parentFile = file.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
                return false;
            }

            fout = new FileOutputStream(file);

            byte[] buffer = new byte[8000];
            int size = 0;
            while ((size = fin.read(buffer)) != -1) {
                fout.write(buffer, 0, size);
            }

            // Notify other applications listening to scanner events
            // that a media file has been added to the sd card
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    } catch (IOException e) {
        // Ignore
        Log.e(TAG, "IOException caught while opening or reading stream", e);
        return false;
    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
        if (null != fout) {
            try {
                fout.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
    }
    return true;
}

From source file:org.mozilla.gecko.GeckoApp.java

private void checkAndLaunchUpdate() {
    Log.i(LOGTAG, "Checking for an update");

    int statusCode = 8; // UNEXPECTED_ERROR
    File baseUpdateDir = null;// ww  w .j a  va  2s  .com
    if (Build.VERSION.SDK_INT >= 8)
        baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    else
        baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");

    File updateDir = new File(new File(baseUpdateDir, "updates"), "0");

    File updateFile = new File(updateDir, "update.apk");
    File statusFile = new File(updateDir, "update.status");

    if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending"))
        return;

    if (!updateFile.exists())
        return;

    Log.i(LOGTAG, "Update is available!");

    // Launch APK
    File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk");
    try {
        if (updateFile.renameTo(updateFileToRun)) {
            String amCmd = "/system/bin/am start -a android.intent.action.VIEW "
                    + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://"
                    + updateFileToRun.getPath();
            Log.i(LOGTAG, amCmd);
            Runtime.getRuntime().exec(amCmd);
            statusCode = 0; // OK
        } else {
            Log.i(LOGTAG, "Cannot rename the update file!");
            statusCode = 7; // WRITE_ERROR
        }
    } catch (Exception e) {
        Log.i(LOGTAG, "error launching installer to update", e);
    }

    // Update the status file
    String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n";

    OutputStream outStream;
    try {
        byte[] buf = status.getBytes("UTF-8");
        outStream = new FileOutputStream(statusFile);
        outStream.write(buf, 0, buf.length);
        outStream.close();
    } catch (Exception e) {
        Log.i(LOGTAG, "error writing status file", e);
    }

    if (statusCode == 0)
        System.exit(0);
}

From source file:com.android.mms.ui.MessageUtils.java

public static File getStorageFile(String filename, Context context) {
    String dir = "";
    String path = StorageManagerEx.getDefaultPath();
    if (path == null) {
        MmsLog.e(TAG, "default path is null");
        return null;
    }//from w w  w.j  ava  2s  . com
    dir = path + "/" + Environment.DIRECTORY_DOWNLOADS + "/";
    MmsLog.i(TAG, "copyPart,  file full path is " + dir + filename);
    File file = getUniqueDestination(dir + filename);

    // make sure the path is valid and directories created for this file.
    File parentFile = file.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        MmsLog.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
        return null;
    }
    return file;
}