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:net.gsantner.opoc.util.ShareUtil.java

/**
 * Request a picture from camera-like apps
 * Result ({@link String}) will be available from {@link Activity#onActivityResult(int, int, Intent)}.
 * It has set resultCode to {@link Activity#RESULT_OK} with same requestCode, if successfully
 * The requested image savepath has to be stored at caller side (not contained in intent),
 * it can be retrieved using {@link #extractResultFromActivityResult(int, int, Intent)},
 * returns null if an error happened./* w  w w.ja v a  2 s  . c  o m*/
 *
 * @param target Path to file to write to, if folder the filename gets app_name + millis + random filename. If null DCIM folder is used.
 */
public String requestCameraPicture(File target) {
    if (!(_context instanceof Activity)) {
        throw new RuntimeException("Error: ShareUtil.requestCameraPicture needs an Activity Context.");
    }
    String cameraPictureFilepath = null;
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(_context.getPackageManager()) != null) {
        File photoFile;
        try {
            // Create an image file name
            if (target != null && !target.isDirectory()) {
                photoFile = target;
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss", Locale.getDefault());
                File storageDir = target != null ? target
                        : new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                                "Camera");
                String imageFileName = ((new ContextUtils(_context).rstr("app_name"))
                        .replaceAll("[^a-zA-Z0-9\\.\\-]", "_") + "_").replace("__", "_")
                        + sdf.format(new Date());
                photoFile = new File(storageDir, imageFileName + ".jpg");
                if (!photoFile.getParentFile().exists() && !photoFile.getParentFile().mkdirs()) {
                    photoFile = File.createTempFile(imageFileName + "_", ".jpg", storageDir);
                }
            }

            //noinspection StatementWithEmptyBody
            if (!photoFile.getParentFile().exists() && photoFile.getParentFile().mkdirs())
                ;

            // Save a file: path for use with ACTION_VIEW intents
            cameraPictureFilepath = photoFile.getAbsolutePath();
        } catch (IOException ex) {
            return null;
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(_context, getFileProviderAuthority(), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            }
            ((Activity) _context).startActivityForResult(takePictureIntent, REQUEST_CAMERA_PICTURE);
        }
    }
    _lastCameraPictureFilepath = cameraPictureFilepath;
    return cameraPictureFilepath;
}

From source file:org.artoolkit.ar.samples.ARMovie.ARMovieActivity.java

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ARCloud");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("ARCloud", "failed to create directory 2");
            return null;
        }//  w  w  w  . j  a  va2s . c  o  m
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}

From source file:com.mobantica.DriverItRide.activities.ActivityProfile.java

private static File getOutputMediaFile(int type) {
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);/*from   ww  w .  j a v a 2s.c  om*/
    try {
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + "/" + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }
    return mediaFile;
}

From source file:info.papdt.blacklight.support.Utility.java

/** Create a File for saving an image*/
private static File getOutputImageFile() {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "BlackLight");
    // 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()) {
            Log.d(TAG, "failed to create directory");
            return null;
        }/* w  ww.  j a va 2s  . c  o  m*/
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    return mediaFile;
}

From source file:org.artoolkit.ar.samples.ARMovie.ARMovieActivity.java

private static File createDataFolders() {
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ARCloud");
    boolean isFolderExisted = false;
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("ARCloud", "failed to create directory 1");
            isFolderExisted = false;//from   ww  w  .  j  a v a2 s  .  co m
            return null;
        } else {
            isFolderExisted = true;
        }
    } else {
        isFolderExisted = true;
    }
    Log.d("ARCloud", mediaStorageDir.getPath());
    if (isFolderExisted) {
        File dataDir = new File(mediaStorageDir.getPath(), "Data");
        if (!dataDir.exists()) {
            if (!dataDir.mkdirs()) {
                return null;
            }
        }
        File dataNFTDir = new File(mediaStorageDir.getPath(), "DataNFT");
        if (!dataNFTDir.exists()) {
            if (!dataNFTDir.mkdirs()) {
                return null;
            }
        }
    }
    return mediaStorageDir;
}

From source file:com.mobileobservinglog.support.HtmlExporter.java

private File getDefaultDirectory() {
    String state = Environment.getExternalStorageState();

    //If the external card is not available, then establish a file location on the internal file system
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    } else {/* w ww. ja  v a2  s  . c  o m*/
        return Environment.getDownloadCacheDirectory();
    }
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * Return Storage Path// w w  w. ja  v  a  2s. c  o  m
 *
 * @return
 */
public static String getStoragePath() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String musicfolderpath = Environment.getExternalStorageDirectory().getAbsolutePath();
        Log.d("Helper", musicfolderpath);
        return musicfolderpath;
    } else {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
    }
}

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

public static void saveAttachmentToExternal(Context context, Attachment attachment, String path) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;//from w  ww .j  a  v  a  2 s .  c  om
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    final long size;
    InputStream in = null;
    OutputStream out = null;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (Utility.isExternalStorageMounted()) {
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // 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");
            }
            // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_S
            try {
                String cachedFileUri = attachment.getCachedFileUri();
                if (TextUtils.isEmpty(cachedFileUri)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(cachedFileUri));
            } catch (IOException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
                //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_S
            } catch (IllegalArgumentException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
            }
            //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_E
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_S
            //Note: we support save attachment at user designated location.
            File downloads;
            if (path != null) {
                downloads = new File(path);
            } else {
                downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_E
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            out = new FileOutputStream(file);
            size = copyFile(in, out);
            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);
            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;
            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } 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.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_S
        //Note:we have saved the attachment to sd card,so should update the attachment destination external
        cv.put(AttachmentColumns.UI_DESTINATION, UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_EXTERNAL);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_E
    } catch (IOException e) {
        // Handle failures here...
        LogUtils.e(Logging.LOG_TAG, "IOException while save an attachment to external storage");
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            LogUtils.e(Logging.LOG_TAG, "ioexception while close the stream");
        }
    }
    // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_E
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_S
    //        context.getContentResolver().update(uri, cv, null, null);
    if (cv.size() > 0) {
        context.getContentResolver().update(uri, cv, null, null);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_E
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        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 + "\"";
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
}

From source file:com.bai.android.ui.OtherActivity.java

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

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "WasedaMobile");
    // 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()) {
            Toast.makeText(getApplicationContext(), "Failed to create directory", Toast.LENGTH_LONG).show();
            return null;
        }/*from ww  w .  j a v a 2 s .co  m*/
    }

    // Create a media file name
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "WasedaMobile_Temp.jpg");

    return Uri.fromFile(mediaFile);
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void runScheduledAlarm(int initialDelay, int period) {
    proximityAlertWatcher = new FiskinfoScheduledTaskExecutor(2).scheduleAtFixedRate(new Runnable() {

        @Override/*from  www.  ja  v  a 2s . com*/
        public void run() {
            // Need to get alarm status and handle kill
            if (!cacheDeserialized) {
                String directoryPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                String directoryName = "FiskInfo";
                String filename = "collisionCheckToolsFile";
                String format = "OLEX";
                String filePath = directoryPath + "/" + directoryName + "/" + filename + "." + format;
                tools = fiskInfoUtility.deserializeFiskInfoPolygon2D(filePath);
                cacheDeserialized = true;
                // DEMO: add point here for testing/demo purposes
                //                         Point point = new Point(69.650543, 18.956831);
                //                         tools.addPoint(point);
            } else {
                if (alarmFiring) {
                    return;
                }

                double latitude, longitude;

                if (mGpsLocationTracker.canGetLocation()) {
                    latitude = mGpsLocationTracker.getLatitude();
                    cachedLat = latitude;
                    longitude = mGpsLocationTracker.getLongitude();
                    cachedLon = longitude;
                    Log.i("GPS-LocationTracker", String.format("latitude: %s, ", latitude));
                    Log.i("GPS-LocationTracker", String.format("longitude: %s", longitude));
                } else {
                    mGpsLocationTracker.showSettingsAlert();
                    return;
                }
                Point userPosition = new Point(cachedLat, cachedLon);

                if (tools.checkCollisionWithPoint(userPosition, cachedDistance)) {
                    alarmFiring = true;
                    Looper.prepare();
                    notifyUserOfProximityAlert();
                }
            }

            System.out.println("Collision check run");
        }

    }, initialDelay, period, TimeUnit.SECONDS);
}