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.qsoft.components.gallery.utils.GalleryUtils.java

public static File getOutputMediaFile(int type) {
    // 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_DCIM),
            "Camera");
    // 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("Camera", "failed to create directory");
            return null;
        }//from   w  w  w . j  ava2s  .  c  om
    }

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

    return mediaFile;
}

From source file:com.lcl6.cn.imagepickerl.AndroidImagePicker.java

/**
 * create a file to save photo//from   w  w  w.j  ava  2 s  .c  o  m
 * @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.gruporaido.tasker_library.util.Helper.java

/**
 * Create a new JPEG file on the public external storage. Uses current timestamp
 * to name the file.//from  w  w  w  .j  av  a2s  .co m
 * <b>Note: Files are accesible to other applications.</b>
 *
 * @return
 * @throws IOException
 */
public File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(imageFileName, ".jpg", storageDir);
}

From source file:org.neotree.ui.fragment.DataExportFragment.java

private boolean exportAsExcelSpreadsheet(ExportData exportData) {
    if (exportData.getEntries() == null || exportData.getEntries().size() == 0) {
        Log.d(TAG, "Nothing to export for script");
        return false;
    }/* w w w.  java  2s.  c o  m*/

    final ArrayList<String> headers = new ArrayList<>();
    final HashMap<String, Integer> columnMap = new HashMap<>();
    final List<Screen> screens = exportData.getScreens();

    int columnIndex = 0;

    for (int screenIndex = 0; screens != null && screenIndex < screens.size(); screenIndex++) {
        final Screen screen = screens.get(screenIndex);
        final ScreenType screenType = ScreenType.fromString(screen.type);
        final Metadata metadata = screen.metadata;

        // Map screen keys
        String screenKey = (TextUtils.isEmpty(metadata.key)) ? null : metadata.key.trim();
        if (screenKey != null && !metadata.confidential) {
            if (screenType == ScreenType.MULTI_SELECT) {
                String itemKey;
                for (int itemIndex = 0; itemIndex < metadata.items.size(); itemIndex++) {
                    final Item item = metadata.items.get(itemIndex);
                    itemKey = String.format("%s_%s", screenKey, item.id);
                    Log.d(TAG, String.format("Mapping item key (multiple selection) [key=%s, index=%d]",
                            itemKey, columnIndex));
                    columnMap.put(itemKey, columnIndex++);
                    headers.add(itemKey);
                }
            } else {
                Log.d(TAG, String.format("Mapping screen key [key=%s, index=%d]", screenKey, columnIndex));
                columnMap.put(screenKey, columnIndex++);
                headers.add(screenKey);
            }
        } else {
            if (screenType == ScreenType.FORM) {
                // Map field keys
                String fieldKey = null;
                if (metadata.fields != null && metadata.fields.size() > 0) {
                    for (int fieldIndex = 0; fieldIndex < metadata.fields.size(); fieldIndex++) {
                        final Field field = metadata.fields.get(fieldIndex);
                        fieldKey = (TextUtils.isEmpty(field.key)) ? null : field.key.trim();

                        if (fieldKey != null && !field.confidential) {
                            Log.d(TAG, String.format("Mapping field key [key=%s, index=%d]", fieldKey,
                                    columnIndex));
                            columnMap.put(fieldKey, columnIndex++);
                            headers.add(fieldKey);
                        }
                    }
                }
            } else {
                // Map item keys
                if (metadata.items != null) {
                    if (screenType == ScreenType.CHECKLIST) {
                        String itemKey;
                        for (int itemIndex = 0; itemIndex < metadata.items.size(); itemIndex++) {
                            final Item item = metadata.items.get(itemIndex);
                            itemKey = (TextUtils.isEmpty(item.key)) ? null : item.key.trim();

                            if (itemKey != null && !item.confidential) {
                                Log.d(TAG, String.format("Mapping item key (checklist) [key=%s, index=%d]",
                                        itemKey, columnIndex));
                                columnMap.put(itemKey, columnIndex++);
                                headers.add(itemKey);
                            }
                        }
                    }
                }
            }
        }
    }

    WritableWorkbook workbook = null;
    try {
        File exportRootDir = Environment.getExternalStoragePublicDirectory("NeoTree");
        if (!exportRootDir.isDirectory()) {
            if (!exportRootDir.mkdirs()) {
                throw new IOException("Error creating output directory: " + exportRootDir.getAbsolutePath());
            }
        }

        File noMediaFile = new File(exportRootDir, ".nomedia");
        if (!noMediaFile.exists()) {
            if (!noMediaFile.createNewFile()) {
                throw new IOException("Error creating .nomedia file: " + noMediaFile.getAbsolutePath());
            }
        }

        String title = exportData.getScript().title;
        String filename = String.format("%s-%s.xls",
                DateTime.now().toString(DateTimeFormat.forPattern("yyyyMMddHHmm")),
                title.replaceAll("[^a-zA-Z0-9]", "_"));
        File exportFile = new File(exportRootDir, filename);

        Log.d(TAG, "Filename :" + filename);
        Log.d(TAG, "File path:" + exportFile.getAbsolutePath());
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(Locale.ENGLISH);

        workbook = Workbook.createWorkbook(exportFile, wbSettings);

        WritableSheet sheet = workbook.createSheet(title, 0);

        // Add headers
        for (int c = 0; c < headers.size(); c++) {
            sheet.addCell(new Label(c, 0, headers.get(c)));
        }

        // Add rows
        String sessionId = null;
        int rowIndex = 0;

        for (SessionEntry entry : exportData.getEntries()) {
            if (sessionId == null || !sessionId.equals(entry.getSessionId())) {
                sessionId = entry.getSessionId();
                rowIndex++;
            }

            DataType dataType = entry.getDataTypeAsObject();
            switch (dataType) {
            case SET_ID:
                if (entry.getValues() != null) {
                    for (SessionValue value : entry.getValues()) {
                        String itemKey = String.format("%s_%s", value.getKey(), value.getStringValue());
                        try {
                            Label cell = new Label(columnMap.get(itemKey), rowIndex, "Yes");
                            sheet.addCell(cell);
                        } catch (Exception e) {
                            Log.e(TAG, String.format("item key for set does not exist: %s", itemKey), e);
                        }
                    }
                }
                break;
            default:
                String key = entry.getKey();
                try {
                    if (!TextUtils.isEmpty(key) && key.contains(" ")) {
                        key = key.replaceAll("\\s+", "");
                    }

                    String content = entry.getSingleValue().getValueAsExportString(getActivity());
                    sheet.addCell(new Label(columnMap.get(key), rowIndex, content));
                } catch (Exception e) {
                    Log.e(TAG, String.format("item key does not exist: %s", key), e);
                }
            }
        }

        workbook.write();

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(getActivity(), new String[] { exportFile.toString() }, null,
                (path, uri) -> {
                    Log.d(TAG, String.format("Success exporting data [path=%s, uri=%s]", path, uri));
                });

    } catch (IOException | WriteException e) {
        Log.e(TAG, "Error exporting Excel file", e);
        Crashlytics.logException(e);
        return false;
    } finally {
        try {
            if (workbook != null) {
                workbook.close();
            }
        } catch (IOException | WriteException e) {
            Log.e(TAG, "Error closing workbook file", e);
            Crashlytics.logException(e);
            return false;
        }
    }
    return true;
}

From source file:de.syss.MifareClassicTool.Activities.MainMenu.java

/**
 * Create the directories needed by MCT and clean out the tmp folder.
 *///from ww w. j a  va  2s  .  c  o m
private void initFolders() {
    if (Common.isExternalStorageWritableErrorToast(this)) {
        // Create keys directory.
        File path = new File(
                Environment.getExternalStoragePublicDirectory(Common.HOME_DIR) + "/" + Common.KEYS_DIR);

        if (!path.exists() && !path.mkdirs()) {
            // Could not create directory.
            Log.e(LOG_TAG, "Error while creating '" + Common.HOME_DIR + "/" + Common.KEYS_DIR + "' directory.");
            return;
        }

        // Create dumps directory.
        path = new File(
                Environment.getExternalStoragePublicDirectory(Common.HOME_DIR) + "/" + Common.DUMPS_DIR);
        if (!path.exists() && !path.mkdirs()) {
            // Could not create directory.
            Log.e(LOG_TAG,
                    "Error while creating '" + Common.HOME_DIR + "/" + Common.DUMPS_DIR + "' directory.");
            return;
        }

        // Create tmp directory.
        path = new File(Environment.getExternalStoragePublicDirectory(Common.HOME_DIR) + "/" + Common.TMP_DIR);
        if (!path.exists() && !path.mkdirs()) {
            // Could not create directory.
            Log.e(LOG_TAG, "Error while creating '" + Common.HOME_DIR + Common.TMP_DIR + "' directory.");
            return;
        }
        // Clean up tmp directory.
        for (File file : path.listFiles()) {
            file.delete();
        }

        // Create std. key file if there is none.
        copyStdKeysFilesIfNecessary();
    }
}

From source file:com.android.mail.browse.AttachmentActionHandler.java

private File performAttachmentSave(final Attachment attachment) {
    try {/*  w  w w  . j  a  v a2s  .c om*/
        File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        downloads.mkdirs();
        File file = createUniqueFile(downloads, attachment.getName());
        Uri contentUri = attachment.contentUri;
        InputStream in = mContext.getContentResolver().openInputStream(contentUri);
        OutputStream out = new FileOutputStream(file);
        int size = IOUtils.copy(in, out);
        out.flush();
        out.close();
        in.close();
        String absolutePath = file.getAbsolutePath();
        MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null);
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        dm.addCompletedDownload(attachment.getName(), attachment.getName(),
                false /* do not use media scanner */, attachment.getContentType(), absolutePath, size,
                true /* show notification */);
        Toast.makeText(mContext, mContext.getResources().getString(R.string.save_to) + absolutePath,
                Toast.LENGTH_SHORT).show();
        return file;
    } catch (IOException ioe) {
        // Ignore. Callers will handle it from the return code.
    }

    return null;
}

From source file:com.rnd.snapsplit.view.OcrCaptureFragment.java

/**
 * Handles the requesting of the camera permission.  This includes
 * showing a "Snackbar" message of why the permission is needed then
 * sending the request.//from w  w  w  .j  a  v a2s  . c o  m
 */

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // 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:com.pixelpixel.pyp.MainActivity.java

public void saveFile() throws IOException {
    Drawable drw = img.getDrawable();/*from  ww  w  .j av a2  s. c o m*/
    Bitmap savedPic = ((BitmapDrawable) drw).getBitmap();
    OutputStream fOut = null;

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Pimped pictures");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("Pimp my picture", "failed to create directory");
            return;
        }
    }
    try {
        File picFile = new File(
                mediaStorageDir.getPath() + File.separatorChar + "Pimped_" + timeStamp + ".jpg");
        fOut = new FileOutputStream(picFile);
        picUri = Uri.fromFile(picFile);
        savedPic.compress(Bitmap.CompressFormat.JPEG, 95, fOut);
        fOut.flush();
        fOut.close();
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }
}

From source file:com.att.arocollector.AROCollectorActivity.java

@TargetApi(21)
@Override/*w ww.  j av a2 s  .  co  m*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.i(TAG, "onActivityResult(... requestCode{" + requestCode + "} resultCode{" + resultCode + "} ...)");

    switch (requestCode) {

    case Config.Permission.VPN_PERMISSION_REQUEST_CODE:
        if (resultCode == RESULT_OK) {

            captureVpnServiceIntent = new Intent(getApplicationContext(), CaptureVpnService.class);
            captureVpnServiceIntent.putExtra("TRACE_DIR", Config.TRACE_DIR);
            captureVpnServiceIntent.putExtra(BundleKeyUtil.PRINT_LOG, printLog);

            if (isExternalStorageWritable()) {
                Log.i(TAG, "TRACE_DIR: " + Config.TRACE_DIR + "trace directory: "
                        + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS));

            }

            startService(captureVpnServiceIntent);

            // start collecting META data
            startServices();

            if (doVideoCapture()) {
                getVideoCapturePermission();
            }

        } else if (resultCode == RESULT_CANCELED) {
            showVPNRefusedDialog();
        }

        break;

    case Config.Permission.VIDEO_PERMISSION_REQUEST_CODE:
        Log.i("SecureCollector", "VIDEO_PERMISSION_REQUEST_CODE");
        pushAppToBackStack();

        if (resultCode != RESULT_OK) {
            Toast.makeText(this, "Screen Cast Permission Denied, no SD/HD video will be captured.",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
        videoCapture = new VideoCapture(getApplicationContext(), getWindowManager(), mediaProjection, bitRate,
                screenSize, videoOrient);
        videoCapture.start();
        break;

    default:
        break;
    }
}

From source file:com.hackensack.umc.activity.ProfileActivity.java

private File createImageFile() throws IOException {
    File image = null;//from w w  w.  j a  v  a  2s  .co  m
    File Folder = new File(Environment.getExternalStorageDirectory() + "/.mydir");
    if (Folder.mkdir()) {

        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "/.mydir" + "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    }
    return image;
}