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.dvdprime.mobile.android.ui.DocumentViewActivity.java

@Override
public boolean onContextItemSelected(android.view.MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    default:/*www  . j av a 2 s  . c o  m*/
    case CONTEXT_MENU_COPY_URL:
        SystemUtil.copyToClipboard(mActivity, contextUrl);
        break;
    case CONTEXT_MENU_BROWSER:
        AndroidUtil.clickedLinkAction(mActivity, contextUrl);
        break;
    case CONTEXT_MENU_SHARE_LINK:
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("text/plain");
        localIntent.putExtra("android.intent.extra.TEXT", contextUrl);
        startActivity(Intent.createChooser(localIntent, getString(R.string.action_bar_share_with)));
        break;
    case CONTEXT_MENU_SAVE_IMAGE:
        DownloadManager dm = (DownloadManager) getSystemService("download");
        DownloadManager.Request req = new DownloadManager.Request(Uri.parse(this.contextUrl));
        req.setTitle("DP Downloader");
        req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                StringUtil.substringAfterLast(this.contextUrl, "/"));
        req.setAllowedNetworkTypes(DownloadManager.PAUSED_QUEUED_FOR_WIFI);
        req.setMimeType("image/" + StringUtil.substringAfterLast(contextUrl, "."));
        File localFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (!(localFile.exists()))
            localFile.mkdirs();
        dm.enqueue(req);
        break;
    }

    return false;
}

From source file:io.github.tjg1.nori.ImageViewerActivity.java

/** Create a {@link android.app.DownloadManager.Request} to download an image. */
@NonNull//w ww . j  a  v  a 2 s. c  o m
private DownloadManager.Request getImageDownloadRequest(@NonNull String fileUrl) {
    // Extract file name from URL.
    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    // Create download directory, if it does not already exist.
    //noinspection ResultOfMethodCallIgnored
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();

    // Create and queue download request.
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl)).setTitle(fileName)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
            .setVisibleInDownloadsUi(true);
    // Trigger media scanner to add image to system gallery app on Honeycomb and above.
    request.allowScanningByMediaScanner();
    // Show download UI notification on Honeycomb and above.
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    return request;
}

From source file:es.usc.citius.servando.calendula.fragments.MedicinesListFragment.java

public void downloadProspect(Prescription p) {

    final String uri = PROSPECT_URL.replaceAll("#ID#", p.pid);
    File prospects = new File(
            getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                    + "/prospects/");
    prospects.mkdirs();//from  ww w  . j  a  v a 2s. co  m
    DownloadManager.Request r = new DownloadManager.Request(Uri.parse(uri));

    Log.d("MedicinesListF", "Downloading prospect from  [" + uri + "]");

    r.setDestinationInExternalFilesDir(getActivity(), Environment.DIRECTORY_DOWNLOADS,
            "prospects/" + p.pid + ".pdf");
    r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    r.setVisibleInDownloadsUi(false);
    r.setTitle(p.shortName() + " prospect");
    // Start download
    prospectDowloadCn = p.cn;
    DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    dm.enqueue(r);
}

From source file:co.scandy.example.scandycoreandroidexample.MainActivity.java

void bindScanControls() {
    // Listen for changes to size bar
    ((SeekBar) findViewById(R.id.scan_size)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override//from  w  ww.ja  v  a  2s .  c om
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // Update Scandy Core scan size based on the value of the seekbar
            float x = (float) (((SeekBar) findViewById(R.id.scan_size)).getProgress() * SIZE_STEP_SCALE);
            x += 0.25;
            ScandyCore.setScanSize(x, x, x);

            // Update the TextView with the new scan size
            TextView textView = (TextView) findViewById(R.id.scan_size_text);
            textView.setText(textView.getContentDescription() + " " + x + "m");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    // Listen for changes to resolution bar
    ((SeekBar) findViewById(R.id.scan_resolution))
            .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    // The ScanResolution id is the index of the seekbar + 1 to offset the 0 index.
                    ScanResolution resolution = new ScanResolution(progress + 1, "");
                    // Tell Scandy Core that we want a new resolution
                    ScandyCore.setResolution(resolution);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

    // Listen for clicking on the Mesh button
    ((Button) findViewById(R.id.mesh)).setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Tell Scandy Core to generate a mesh based on the last scan
            ScandyCore.generateMesh();
        }
    });

    // Listen for clicking on the Save button
    ((Button) findViewById(R.id.save)).setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Save the mesh that Scandy Core just generated through scanning
            // NOTE: you could ask a user where to save this scan
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath());
            ScandyCore.saveMesh(
                    dir.getAbsolutePath() + "ScandyCoreAndroidExample-" + System.currentTimeMillis() + ".ply");
        }
    });

    // First initialize all our class Toggle Buttons
    mPreviewToggle = (ToggleButton) findViewById(R.id.preview_toggle);
    mScanToggle = (ToggleButton) findViewById(R.id.scan_toggle);

    // Configure Preview Toggle
    mPreviewToggle.setEnabled(false);
    mPreviewToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Start / stop the preview based on this button
            if (isChecked) {
                ScandyCore.startPreview();
            } else {
                ScandyCore.stopScanning();
            }
        }
    });

    // Configure Scan Toggle
    mScanToggle.setEnabled(false);
    mScanToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Start / stop the scan based on this button
            if (isChecked) {
                ScandyCore.startScanning();
            } else {
                ScandyCore.stopScanning();
            }
        }
    });

}

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*w  w w  . j av  a  2s  .  c om*/
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri;
    long size;
    try {
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            File saveIn = getAttachmentDirectory(context, accountId);
            if (!saveIn.exists()) {
                saveIn.mkdirs();
            }
            File file = getAttachmentFilename(context, accountId, attachmentId);
            file.createNewFile();
            size = copyFile(in, file);
            contentUri = getAttachmentUri(accountId, attachmentId).toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, file);
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            Log.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

}

From source file:com.chen.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///  www. ja  v  a2s . c om
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.handpoint.headstart.client.ui.ReceiptActivity.java

private File getOutputMediaFile(String prefix) {
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        return null;
    }//www.  j ava 2s  . c  o  m
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator
                    + "HandpointProducts");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            logger.log(Level.SEVERE, TAG + " :Failed to create directory for storing receipt");
            return null;
        }
    }
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile = new File(mediaStorageDir, prefix + "receipt_" + timeStamp + ".pdf");
    return mediaFile;
}

From source file:com.jwetherell.quick_response_code.EncoderActivity.java

public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;/*  www.  j  av a 2 s  . c  o m*/
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "miwifiQR_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

From source file:locationkitapp.locationkit.locationkitapp.MapsActivity.java

private void emailVisitHistory() {
    ArrayList<Uri> uris = new ArrayList<Uri>();
    String filename = String.format(Locale.ENGLISH, "data_%d.csv", System.currentTimeMillis());
    File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(root, filename);
    if (!file.exists()) {
        try {/*www.  j a  va 2 s  .c o  m*/
            file.createNewFile();
        } catch (IOException e) {
            Log.e(LOG_TAG, "file failed", e);
            return;
        }
    }
    try {
        FileOutputStream os = new FileOutputStream(file);
        os.write(
                "arrival_date,detected_time,visit_id,departure_date,category,subcategory,venue_name,street,city,state,zip,detection_method,latitude,longitude,from_place\n"
                        .getBytes());
        for (Visit v : mVisits) {
            os.write(visitRow(v).getBytes());
        }
        os.close();
    } catch (IOException e) {
        Log.e(LOG_TAG, "ioexception on file", e);
        return;
    }
    uris.add(LKDataManager.EXPORT_DB(this));
    Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "LocationKitApp ");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Visits Recorded by LocationKitApp");
    uris.add(Uri.fromFile(file));
    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
}

From source file:com.indeema.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from w w  w.  j  a v  a2 s.  co m*/
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            if (attachment.mFileName == null) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}