Example usage for android.os Environment getExternalStoragePublicDirectory

List of usage examples for android.os Environment getExternalStoragePublicDirectory

Introduction

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

Prototype

public static File getExternalStoragePublicDirectory(String type) 

Source Link

Document

Get a top-level shared/external storage directory for placing files of a particular type.

Usage

From source file:com.wit.android.support.content.intent.ContentIntent.java

/**
 * Same as {@link #createContentFile(String, String, java.io.File)} with <b>.jpg</b> as <var>imageType</var>
 * and {@link android.os.Environment#getExternalStoragePublicDirectory(String)} with {@link android.os.Environment#DIRECTORY_PICTURES}
 * as <var>directory</var>.//from  ww  w  .j av  a 2s  . co m
 *
 * @param fileName                 Desired name for the requested file.
 * @param environmentDirectoryType One of {@link Environment#DIRECTORY_PICTURES}, {@link Environment#DIRECTORY_MOVIES}, ....
 */
@Nullable
protected static File createContentFile(@NonNull String fileName, @Nullable String fileType,
        @NonNull String environmentDirectoryType) {
    return createContentFile(fileName, fileType,
            Environment.getExternalStoragePublicDirectory(environmentDirectoryType));
}

From source file:de.baumann.browser.Browser.java

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yy-MM-dd_HH-mm", Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );//from   w ww  . j a va 2s .  co  m
}

From source file:org.opendatakit.survey.activities.MediaCaptureVideoActivity.java

private File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            WebLogger.getLogger(appName).d(t, "failed to create directory");
            return null;
        }//w  w w  .j  a v  a  2 s. c  o m
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSSZ", Locale.US).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

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

/** Create a {@link android.app.DownloadManager.Request} to download an image. */
@NonNull/*from ww  w .  ja v  a 2  s .c om*/
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:nazmul.storagesampletest.MainActivity.java

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );//from ww  w.j a v a 2 s .c  om
    foodPhotoPath = image.getAbsolutePath();
    mFileUri = Uri.fromFile(image);
    return image;
}

From source file:com.anhubo.anhubo.ui.activity.unitDetial.UploadingActivity1.java

/**
 * ?? ?????//ww w . j a  v a2 s.c  o  m
 **/
private File savePicture(Bitmap bitmap, String fileName) {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File outputImage = new File(path, fileName + ".jpg");
    try {
        if (outputImage.exists()) {
            outputImage.delete();
        }
        outputImage.createNewFile();
        OutputStream stream = new FileOutputStream(outputImage);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);// 
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
    return outputImage;
}

From source file:net.jongrakko.zipsuri.activity.PostUploadActivity.java

private void takeImage() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    takeFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Zisuri_tmp_" + System.currentTimeMillis() + ".jpg");
    Uri saveUri = Uri.fromFile(takeFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // set the image file name
    startActivityForResult(intent, TAKE_PHOTO_FOR_AVATAR);
}

From source file:com.pizidea.imagepicker.AndroidImagePicker.java

/**
 * create a file to save photo/*w  w w. ja  v  a 2s .c  om*/
 *
 * @param ctx
 * @return
 */
private File createImageSaveFile(Context ctx) {
    if (Util.isStorageEnable()) {
        // 
        File pic = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!pic.exists()) {
            pic.mkdirs();
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String fileName = "IMG_" + timeStamp;
        File tmpFile = new File(pic, fileName + ".jpg");
        mCurrentPhotoPath = tmpFile.getAbsolutePath();
        Log.i(TAG, "=====camera path:" + mCurrentPhotoPath);
        return tmpFile;
    } else {
        //File cacheDir = ctx.getCacheDir();
        File cacheDir = Environment.getDataDirectory();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String fileName = "IMG_" + timeStamp;
        File tmpFile = new File(cacheDir, fileName + ".jpg");
        mCurrentPhotoPath = tmpFile.getAbsolutePath();
        Log.i(TAG, "=====camera path:" + mCurrentPhotoPath);
        return tmpFile;
    }
}

From source file:com.retroteam.studio.retrostudio.EditorLandscape.java

/**
 * Write the 8bit PCM audio to the wav file format to the public music dir.
 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
 * @param proj//w  w  w . jav  a 2s  . co  m
 * @param filename
 */

private void exportAsWav(Project proj, String filename) {
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                filename + ".wav");
        DataOutputStream os = new DataOutputStream(new FileOutputStream(file));

        // get project length
        int pLength = proj.export().getBytes().length;

        os.writeBytes("RIFF"); // Chunk ID 'RIFF'
        os.write(intToByteArray(36 + pLength), 0, 4); //file size
        os.writeBytes("WAVE"); // Wave ID
        os.writeBytes("fmt "); // Chunk ID 'fmt '
        os.write(intToByteArray(16), 0, 4); // chunk size
        os.write(intToByteArray(1), 0, 2); // pcm audio
        os.write(intToByteArray(1), 0, 2); // mono
        os.write(intToByteArray(8000), 0, 4); // samples/sec
        os.write(intToByteArray(pLength), 0, 4); // bytes/sec
        os.write(intToByteArray(1), 0, 2); // 1 byte/sample
        os.write(intToByteArray(8), 0, 2); // 8 bits/sample
        os.writeBytes("data"); // Chunk ID 'data'
        os.write(intToByteArray(pLength), 0, 4); // size of data chunk
        os.write(proj.export().getBytes()); // write the data
        os.close();
        Toast.makeText(this, "Saved file to: " + file.getPath(), Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(this, "IOException while saving project.", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Fragment fragmentParent,
        final Action action) {

    final Activity activity = fragmentParent.getSupportActivity();

    switch (action) {

    case UPVOTE://  w  w  w  . j av a 2  s  .  c o m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(post.url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            General.copyFile(cacheFile.getInputStream(), dst);
                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        final RedditSubreddit subreddit = new RedditSubreddit("/r/" + post.src.subreddit,
                "/r/" + post.src.subreddit, true);

        final Intent intent = new Intent(activity, PostListingActivity.class);
        intent.putExtra("subreddit", subreddit);
        activity.startActivityForResult(intent, 1);
        break;
    }

    case USER_PROFILE:
        UserProfileDialog.newInstance(post.src.author).show(activity);
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, fragmentParent, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}