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.business.rushour.businessapp.RiderMainActivity.java

private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);/*from  w w  w.j  a  v  a  2s.c o m*/

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

    } else {
        return null;
    }

    return mediaFile;
}

From source file:org.wso2.iot.agent.services.FileDownloadService.java

private String getSavingLocation() {
    if (!Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).exists()
            && !Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs()) {
        return null;
    }/* ww  w. j  a  v a2 s.co  m*/
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
}

From source file:it.rignanese.leo.slimfacebook.MainActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );//from  w w w  . ja v a2  s  .co m
    return imageFile;
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public void imageOpen(Fragment f, final int REQUEST_CAMERA, final int SELECT_FILE) {

    GeneralHelper.getInstance(MainActivity.this).setTempFragment(f);
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override/*from ww w  .j a va2  s.  c  om*/
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {

                java.io.File imageFile = new File(
                        (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                                + Constants.APPNAME + "/" + System.currentTimeMillis() + ".jpeg"));

                PreferencesManager.setPreferenceByKey(MainActivity.this, "IMAGEWWC",
                        imageFile.getAbsolutePath());
                //
                imageFilePath = imageFile;
                imageFileUri = Uri.fromFile(imageFile);
                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(i, REQUEST_CAMERA);

            } else if (items[item].equals("Choose from Library")) {
                if (Build.VERSION.SDK_INT < 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                }

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

From source file:com.eggwall.SoundSleep.AudioService.java

/**
 * [sdcard]/music in SDK >= 8/*from  w  w  w.j a v  a 2  s  .  c  om*/
 * @return the [sdcard]/music path in sdk version >= 8
 */
private static File getMusicDirAfterV8() {
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
}

From source file:com.dazone.crewchat.libGallery.activity.BucketHomeFragmentActivity.java

/**
 * Create a File for saving an image or video
 */// w  ww.  ja  v a  2  s. com
private static File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            MediaChooserConstants.folderName);
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

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

    return mediaFile;
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.FiskInfoUtility.java

public boolean writeMapLayerToExternalStorage(Activity activity, byte[] data, String writableName,
        String format, String downloadSavePath, boolean showToasts) {

    if (FiskInfoUtility.shouldAskPermission()) {
        String[] perms = { "android.permission.WRITE_EXTERNAL_STORAGE" };
        int permsRequestCode = 0x001;
        //            activity.requestPermissions(perms, permsRequestCode);

        ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                permsRequestCode);/*from w w  w  . j  a v a  2s .  co m*/
    }

    String filePath;
    OutputStream outputStream = null;
    filePath = downloadSavePath;
    boolean success = false;
    String fileEnding = format;

    File directory = filePath == null ? null : new File(filePath);

    if (directory != null && !directory.isDirectory() && !directory.mkdirs()) {
        directory = null;
    }

    if (directory == null) {
        String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .toString();
        String directoryName = "FiskInfo";
        filePath = directoryPath + "/" + directoryName + "/";
        new File(filePath).mkdirs();
    }

    if (fileEnding != null && fileEnding.equals(activity.getBaseContext().getString(R.string.olex))) {
        fileEnding = "olx.gz";
    }

    try {
        File dir = new File(filePath);
        File file = new File(filePath + writableName + "." + fileEnding);

        if (!dir.canWrite()) {
            Toast.makeText(activity.getBaseContext(), R.string.error_cannot_write_to_directory,
                    Toast.LENGTH_LONG);
            throw new IOException(activity.getResources().getString(R.string.error_cannot_write_to_directory));
        }

        // index 1 is leef when plugged in. Dirs[1].getAbsoluteFile() is writable
        //            File[] dirs = ContextCompat.getExternalFilesDirs(activity.getBaseContext(), null);

        outputStream = new FileOutputStream(file);
        outputStream.write(data);

        if (showToasts) {
            Toast.makeText(activity.getBaseContext(), "Fil lagret til " + filePath, Toast.LENGTH_LONG).show();
        }

        success = true;
    } catch (IOException e) {
        if (showToasts) {
            Toast.makeText(activity.getBaseContext(), R.string.disk_write_failed, Toast.LENGTH_LONG).show();
        }
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return success;
}

From source file:com.microsoft.mimickeralarm.ringing.ShareFragment.java

public void download() {
    File cameraDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

    File sourceFile = new File(mShareableUri);
    String dateTimeString = (new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(new Date())); // Example: 2015-12-31-193205
    String targetFileName = MIMICKER_FILE_PREFIX + dateTimeString + ".jpg"; // "Mimicker_2015-12-31-193205.jpg
    File targetFile = new File(cameraDirectory.getPath(), targetFileName);

    try {//w w  w.  j a va2  s .co  m
        copyFile(sourceFile, targetFile);
    } catch (IOException ex) {
        showToastInFragment(R.string.share_download_failure);
        Logger.trackException(ex);
        return;
    }

    // Inform the media store about the new file
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, targetFile.getPath());
    getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    showToastInFragment(R.string.share_download_success);
}

From source file:simonlang.coastdove.usagestatistics.utility.FileHelper.java

public static File getFile(Context context, Directory directory, String appPackageName, String filename) {
    String publicDirectory = context.getString(R.string.external_folder_name);
    File baseDirectory;/*w  ww.  j av  a 2  s  . co m*/
    String subDirectory;
    switch (directory) {
    case PRIVATE:
        baseDirectory = context.getFilesDir();
        subDirectory = "";
        break;
    case PUBLIC:
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Log.e("FileHelper", "External storage is not mounted, failing.");
            return null;
        }
        baseDirectory = Environment.getExternalStoragePublicDirectory(publicDirectory);
        subDirectory = "";
        break;
    case PRIVATE_PACKAGE:
        baseDirectory = context.getFilesDir();
        if (appPackageName == null)
            throw new IllegalArgumentException("appPackageName must not be null");
        subDirectory = appPackageName + "/";
        break;
    case PUBLIC_PACKAGE:
        if (appPackageName == null)
            throw new IllegalArgumentException("appPackageName must not be null");
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Log.e("FileHelper", "External storage is not mounted, failing.");
            return null;
        }
        baseDirectory = Environment.getExternalStoragePublicDirectory(publicDirectory);
        subDirectory = appPackageName + "/";
        break;
    default:
        throw new IllegalArgumentException("directory must be specified (see FileHelper.Directory)");
    }

    File file = new File(baseDirectory, subDirectory + filename);
    return file;
}

From source file:es.upv.riromu.arbre.main.MainActivity.java

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState.containsKey("cropping")) {
        state[CROP_IMAGE] = savedInstanceState.getBoolean("cropping");
    }//w  w  w .  j  a v  a 2  s  .  co  m
    if (savedInstanceState.containsKey("treated")) {
        state[TREAT_IMAGE] = savedInstanceState.getBoolean("treated");
    }

    if (savedInstanceState.containsKey("image_uri")) {
        image_uri = Uri.parse(savedInstanceState.getString("image_uri"));
    }

    if (savedInstanceState.getBoolean("image")) {
        String fileName = "temp_image.jpg";
        String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath()
                + "/" + fileName;
        File file = new File(fileURL);
        try {
            InputStream imageStream = getContentResolver().openInputStream(Uri.fromFile(file));
            image = Util.decodeScaledBitmapFromFile(file.getPath(), MAX_SIZE, MAX_SIZE);
            //  image = BitmapFactory.decodeStream(imageStream);

        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    if (state[CROP_IMAGE]) {
        String fileName = "temp_cropped.jpg";
        String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath()
                + "/" + fileName;
        File file = new File(fileURL);
        try {
            InputStream imageStream = getContentResolver().openInputStream(Uri.fromFile(file));
            croppedimage = BitmapFactory.decodeStream(imageStream);
            imageStream.close();
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }
    if (state[TREAT_IMAGE]) {
        String fileName = "temp_treated.jpg";
        String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath()
                + "/" + fileName;
        File file = new File(fileURL);
        try {
            InputStream imageStream = getContentResolver().openInputStream(Uri.fromFile(file));
            ImageView imv = (ImageView) findViewById(R.id.image_intro);
            imv.setImageBitmap(BitmapFactory.decodeStream(imageStream));
            imageStream.close();
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }
    ImageView imv = (ImageView) findViewById(R.id.image_intro);
    colours = savedInstanceState.getIntArray("colours");
    if ((!state[TREAT_IMAGE]) && state[CROP_IMAGE])
        imv.setImageBitmap(croppedimage);
    else {

        imv.setImageBitmap(image);
    }
    TextView imc = (TextView) findViewById(R.id.textView);
    imc.setBackgroundColor(Color.rgb(colours[COLOUR_R], colours[COLOUR_G], colours[COLOUR_B]));
}