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:de.skubware.opentraining.activity.create_exercise.ImageFragment.java

/**
 * Generates a unique filename and creates an empty file to use.
 * //from  www  .  j  a  v a2 s .c o  m
 * 
 * @param internal For use within this app an internal folder is the right choice.
 * If the Uri should be passed to another app(e.g. camera app) an external folder has to be created.
 * Otherwise external apps cannot acces the folder.
 * 
 * @return
 * @throws IOException
 */
private Uri createImageFile(boolean internal) throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File customImageFolder;
    if (internal) {
        customImageFolder = new File(
                getActivity().getFilesDir().toString() + "/" + IDataProvider.CUSTOM_IMAGES_FOLDER);
    } else {
        customImageFolder = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "OpenTraining");
    }
    if (!customImageFolder.exists()) {
        customImageFolder.mkdirs();
        Log.d(TAG, "Folder for custom exercise images does not exist, will create it now.");
    }

    File image = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            customImageFolder /* directory */
    );

    return Uri.fromFile(image);
}

From source file:ufms.br.com.ufmsapp.fragment.MateriaisEventoFragment.java

@Override
public void onMaterialClick(View v, int position, final Material material) {

    if (RequestPermission.verifyStoragePermissions(getActivity())) {
        String fileName = material.getPathMaterial().replace(DownloadTask.UPLOAD_PATH_REPLACE, "");
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                fileName);/*from   ww  w.j a  va 2 s  . co  m*/

        switch (v.getId()) {
        case R.id.root_open_document:
            if (file.exists()) {
                openDocument(material.getPathMaterial());
            } else {
                final DownloadTask downloadTask = new DownloadTask(getActivity(),
                        R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                        getActivity().getResources().getString(R.string.txt_download_em_progresso),
                        getActivity());
                downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                openDocument(material.getPathMaterial());
            }
            break;
        case R.id.btn_file_download:

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
            boolean networkTypeWifi = prefs.getBoolean(getResources().getString(R.string.pref_network_type),
                    true);

            //Se existir o arquivo, no baixa novamente
            if (!file.exists()) {
                if (ConnectionUtils.isConnectedWifi(getActivity())) {
                    final DownloadTask downloadTask = new DownloadTask(getActivity(),
                            R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                            getActivity().getResources().getString(R.string.txt_download_em_progresso),
                            getActivity());
                    downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                } else if (ConnectionUtils.isConnectedMobile(getActivity()) && !networkTypeWifi) {
                    final DownloadTask downloadTask = new DownloadTask(getActivity(),
                            R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                            getActivity().getResources().getString(R.string.txt_download_em_progresso),
                            getActivity());
                    downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            R.string.txt_wifi_only_snackbar, Snackbar.LENGTH_LONG).show();
                }

            } else {

                final Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content),
                        R.string.txt_success_download_snack_bar, Snackbar.LENGTH_LONG);

                snackbar.setAction(R.string.txt_open_document, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        openDocument(material.getPathMaterial());

                    }
                }).show();

                //Snackbar.make(getActivity().findViewById(android.R.id.content), R.string.txt_success_download_snack_bar, Snackbar.LENGTH_LONG).show();
            }
            break;
        }

    } else {
        Toast.makeText(MyApplication.getAppContext(), "Para baixar os materiais, ative a permisso",
                Toast.LENGTH_LONG).show();
    }

}

From source file:com.albedinsky.android.support.intent.ContentIntent.java

/**
 * Same as {@link #createContentFile(String, File)} with <b>directory</b> obtained
 * via {@link Environment#getExternalStoragePublicDirectory(String)} with the specified
 * <var>externalDirectoryType</var> as <var>type</var>.
 *
 * @param fileName              The desired name for the requested file.
 * @param externalDirectoryType One of {@link Environment#DIRECTORY_PICTURES}, {@link Environment#DIRECTORY_MOVIES}, ....
 *///from   w  w w. j a  v  a2 s  .co m
@Nullable
public static File createContentFile(@NonNull String fileName, @NonNull String externalDirectoryType) {
    return createContentFile(fileName, Environment.getExternalStoragePublicDirectory(externalDirectoryType));
}

From source file:it.smartcampuslab.riciclo.FeedbackFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (resultCode != 0) {
            // Uri imgUri = data.getData();
            File mediaStorageDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

            File fi = new File(mediaStorageDir + File.separator + "tmpImg.jpg");
            if (fi.exists()) {
                try {
                    Uri imgUri = Uri.parse(android.provider.MediaStore.Images.Media
                            .insertImage(getActivity().getContentResolver(), fi.getAbsolutePath(), null, null));
                    imageUri = imgUri.toString();
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(fi.getAbsolutePath(), options);

                    options.inSampleSize = calculateInSampleSize(options, dpToPx(IMG_HEIGHT),
                            dpToPx(IMG_HEIGHT));
                    options.inJustDecodeBounds = false;
                    Bitmap myBitmap = BitmapFactory.decodeFile(fi.getAbsolutePath(), options);

                    ImageView myImage = (ImageView) getView().findViewById(R.id.feedback_img_result);
                    myImage.setVisibility(View.VISIBLE);
                    myImage.setImageBitmap(myBitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("CaptureHelper", "Error reading image");
                }//from   w w w .ja  v  a  2  s .  c  o  m
            }
        }

    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static File getPublicAttachmentsDirectory(String type) {
    File pictures = Environment.getExternalStoragePublicDirectory(type);
    File directory = new File(pictures, "MAGE");

    if (!directory.exists()) {
        directory.mkdirs();//from  w w  w .j  a v a  2s.c  o  m
    }

    return directory;
}

From source file:tjs.tuneramblr.CheckinFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.checkin, container, false);

    // get a handle on the UI elements
    addSongButton = (Button) view.findViewById(R.id.addButton);
    takePhotoButton = (Button) view.findViewById(R.id.takePhotoBtn);
    trackNameText = (TextView) view.findViewById(R.id.trackNameText);
    artistNameText = (TextView) view.findViewById(R.id.artistNameText);
    albumNameText = (TextView) view.findViewById(R.id.albumNameText);
    doingWhatText = (EditText) view.findViewById(R.id.doing_what);

    // update the track display
    populateTrackDisplay(getActivity().getApplicationContext());

    // listeners/*from   w ww.  j  a  va  2  s  .c  om*/
    addSongButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ILastLocationFinder locationFinder = PlatformSpecificImplementationFactory
                    .getLastLocationFinder(v.getContext());

            TrackInfoDS tids = new TrackInfoDS(v.getContext());

            // build an Intent to send over to the checkin service
            Intent trackCheckinIntent = new Intent(v.getContext(), TrackCheckinService.class);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_IMG_URI_KEY, imageUri);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_LOCATION_KEY, locationFinder
                    .getLastBestLocation(TuneramblrConstants.MAX_DISTANCE, TuneramblrConstants.MAX_TIME));
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_TRACK_CHECKIN_TYPE_KEY,
                    CheckinType.USER_LIKE);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_DOING_WHAT_KEY,
                    doingWhatText.getText().toString());

            tids.open();
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_TRACK_INFO_KEY, tids.getLastRecordedTrack());
            tids.close();

            v.getContext().startService(trackCheckinIntent);

            // notify the user that the track has been sent
            Toast songResultText = Toast.makeText(v.getContext(), R.string.songSubmitted, Toast.LENGTH_LONG);
            songResultText.show();

            // clear the image URI
            imageUri = null;

            // clear the text area
            doingWhatText.setText("");
        }
    });

    takePhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // use the stock camera and save the image to some location on
            // the phone/SDCARD
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageUri = getImageUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TuneramblrMobileActivity.TAKE_PHOTO_CODE);
        }

        /** Create a File for saving an image */
        public File buildOutputMediaFile() {

            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "tuneramblr");

            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("tuneramblr", "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(), "IMG_TR_" + timeStamp + ".jpg");

            return mediaFile;
        }

        /**
         * Get the uri of the captured file
         * 
         * @return A Uri which path is the path of an image file, stored on
         *         the dcim folder
         */
        public Uri getImageUri() {
            // Store image in dcim
            File file = buildOutputMediaFile();
            Uri imu = Uri.fromFile(file);

            return imu;
        }
    });

    // this is just to update the UI as new track information is received.
    // this uses the meta media intent filter.
    getActivity().registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // pull the track info from the intent
            String track = intent.getStringExtra("track");
            String artist = intent.getStringExtra("artist");
            String album = intent.getStringExtra("album");

            // update the UI elements
            trackNameText.setText(track);
            artistNameText.setText(artist);
            albumNameText.setText(album);

        }
    }, MetaMediaRequester.buildMediaIntentFilter());

    return view;
}

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

/**
 * Initializes the UI and creates the detector pipeline.
 *//*from  www . j a  v  a2  s.c  om*/
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
//            Toast.makeText(getContext(), "pic saved", Toast.LENGTH_LONG).show();
//            Log.d("CameraDemo", "Pic saved");
//        }
//    }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.view_ocr_capture, container, false);
    final Activity activity = getActivity();
    final Context context = getContext();

    ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger))
            .setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));
    final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + "/picFolder/";
    File newdir = new File(dir);
    newdir.mkdirs();

    mPreview = (CameraSourcePreview) view.findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) view.findViewById(R.id.graphicOverlay);

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

    // Set good defaults for capturing text.
    boolean autoFocus = true;
    boolean useFlash = false;

    //        createNewThread();
    //        t.start();

    final ImageView upArrow = (ImageView) view.findViewById(R.id.arrow_up);
    upArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (rotationAngle == 0) { // arrow up
                //mCameraSource.takePicture(null, mPicture);
                //mGraphicOverlay.clear();
                //                    mGraphicOverlay.clear();
                //                    mGraphicOverlay.amountItem = null;
                onPause();
                //shouldContinue = false;
                //mCamera.takePicture(null, null, mPicture);

                File pictureFile = getOutputMediaFile();
                if (pictureFile == null) {
                    return;
                }
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
                    receiptBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    picPath = pictureFile.getAbsolutePath();
                    //fos.write(mCameraSource.mostRecentBitmap);
                    fos.close();
                } catch (FileNotFoundException e) {

                } catch (IOException e) {
                }

                upArrow.animate().rotation(180).setDuration(500).start();

                TextView amount = (TextView) view.findViewById(R.id.text_amount_value);
                if (mGraphicOverlay.amountItem == null) {
                    amount.setText("0.00");
                } else {
                    amount.setText(String.format("%.2f", mGraphicOverlay.amountItemAfterFormat));
                }
                TextView desc = (TextView) view.findViewById(R.id.text_name_value);
                desc.setText(mGraphicOverlay.description);

                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                box.setVisibility(View.VISIBLE);
                Animation slide_up = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_up);

                box.startAnimation(slide_up);
                rotationAngle = 180;

            } else {
                //                    t.interrupt();
                //                    t = null;
                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                Animation slide_down = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_down);

                upArrow.animate().rotation(0).setDuration(500).start();

                box.startAnimation(slide_down);
                box.setVisibility(View.INVISIBLE);
                //shouldContinue = true;
                mGraphicOverlay.amountItem = null;
                mGraphicOverlay.amountItemAfterFormat = 0f;
                mGraphicOverlay.description = "";
                onResume();
                //                    createNewThread();
                //                    t.start();
                rotationAngle = 0;
            }
        }
    });

    ImageView addButton = (ImageView) view.findViewById(R.id.add_icon);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // takePicture();
            EditText description = (EditText) view.findViewById(R.id.text_name_value);
            EditText amount = (EditText) view.findViewById(R.id.text_amount_value);
            float floatAmount = Float.parseFloat(amount.getText().toString());
            Summary t = new Summary(description.getText().toString(), floatAmount);

            Bundle bundle = new Bundle();
            bundle.putSerializable("splitTransaction", t);

            //                 ByteArrayOutputStream stream = new ByteArrayOutputStream();
            //                 mCameraSource.mostRecentBitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
            //                 byte[] byteArray = stream.toByteArray();
            //Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
            //bundle.putParcelable("receiptPicture",receiptBitmap);
            bundle.putString("receiptPicture", picPath);

            FriendsSelectionFragment fragment = new FriendsSelectionFragment();
            fragment.setArguments(bundle);

            ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger)).setVisibility(View.INVISIBLE);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_holder, fragment, "FriendsSelectionFragment").addToBackStack(null)
                    .commit();
        }
    });

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {
        requestCameraPermission();
    }

    gestureDetector = new GestureDetector(context, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());

    //        Snackbar.make(mGraphicOverlay, "Tap to Speak. Pinch/Stretch to zoom",
    //                Snackbar.LENGTH_LONG)
    //                .show();

    // Set up the Text To Speech engine.
    TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(final int status) {
            if (status == TextToSpeech.SUCCESS) {
                Log.d("OnInitListener", "Text to speech engine started successfully.");
                tts.setLanguage(Locale.US);
            } else {
                Log.d("OnInitListener", "Error starting the text to speech engine.");
            }
        }
    };
    tts = new TextToSpeech(activity.getApplicationContext(), listener);

    return view;
}

From source file:MainActivity.java

private File getPictureFile() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(System.currentTimeMillis());
    String fileName = "PHOTO_" + timeStamp + ".jpg";
    return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
}

From source file:ufms.br.com.ufmsapp.fragment.MateriaisDisciplinaFragment.java

@Override
public void onMaterialClick(View v, int position, final Material material) {

    if (RequestPermission.verifyStoragePermissions(getActivity())) {
        String fileName = material.getPathMaterial().replace(DownloadTask.UPLOAD_PATH_REPLACE, "");
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                fileName);// www .  j a va2 s  . com

        switch (v.getId()) {
        case R.id.root_open_document:
            if (file.exists()) {
                openDocument(material.getPathMaterial());
            } else {
                final DownloadTask downloadTask = new DownloadTask(getActivity(),
                        R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                        getActivity().getResources().getString(R.string.txt_download_em_progresso),
                        getActivity());
                downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                openDocument(material.getPathMaterial());
            }
            break;
        case R.id.btn_file_download:

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
            boolean networkTypeWifi = prefs.getBoolean(getResources().getString(R.string.pref_network_type),
                    true);

            //Se existir o arquivo, no baixa novamente
            if (!file.exists()) {
                if (ConnectionUtils.isConnectedWifi(getActivity())) {
                    final DownloadTask downloadTask = new DownloadTask(getActivity(),
                            R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                            getActivity().getResources().getString(R.string.txt_download_em_progresso),
                            getActivity());
                    downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                } else if (ConnectionUtils.isConnectedMobile(getActivity()) && !networkTypeWifi) {
                    final DownloadTask downloadTask = new DownloadTask(getActivity(),
                            R.mipmap.ic_file_download_black_24dp, material.getPathMaterial(),
                            getActivity().getResources().getString(R.string.txt_download_em_progresso),
                            getActivity());
                    downloadTask.execute(UrlEndpoints.URL_ENDPOINT_DOWNLOAD_FILE + material.getPathMaterial());
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            R.string.txt_wifi_only_snackbar, Snackbar.LENGTH_LONG).show();
                }

            } else {

                final Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content),
                        R.string.txt_success_download_snack_bar, Snackbar.LENGTH_LONG);

                snackbar.setAction(R.string.txt_open_document, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        openDocument(material.getPathMaterial());

                    }
                }).show();
            }
            break;
        }

    } else {
        Toast.makeText(MyApplication.getAppContext(), "Para baixar os materiais, ative a permisso",
                Toast.LENGTH_LONG).show();
    }

}

From source file:com.app.swaedes.swaedes.OtherSitePage.java

public File getOutputAudioFile(int type) {

    //Create folder if it doesn't exist
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
            Config.APP_DIRECTORY_NAME);/*from w  w w. ja  va  2  s  .  com*/

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(Config.APP_DIRECTORY_NAME,
                    "Oops! Failed to create" + Config.APP_DIRECTORY_NAME + "directory");
            return null;
        }
    }

    //Audio title will be a timestamp to be unique
    audio_name = "REC_" + Config.timeStamp() + ".3gp";
    File audioFile;
    if (type == MEDIA_TYPE_AUDIO) {
        audioFile = new File(mediaStorageDir + File.separator + audio_name);
    } else {
        return null;
    }
    return audioFile;
}