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:org.crossconnect.bible.activity.main.ResourceFragment.java

@Override
public void onListItemClick(ListView l, View v, int pos, long id) {

    final int position = pos;

    //Get the corresponding resource
    final OnlineAudioResource resource = mAdapter.getItem(position);

    final ActionItem readAction = new ActionItem();

    readAction.setTitle("Read");
    readAction.setIcon(getResources().getDrawable(R.drawable.icon_read));

    final ActionItem playAction = new ActionItem();

    playAction.setTitle("Play");
    playAction.setIcon(getResources().getDrawable(R.drawable.icon_play));

    final ActionItem downloadAction = new ActionItem();

    downloadAction.setTitle("Download");
    downloadAction.setIcon(getResources().getDrawable(R.drawable.icon_download));

    final QuickActionHorizontal mQuickAction = new QuickActionHorizontal(v);

    if (resource.getReadURL() != null) {
        readAction.setOnClickListener(new OnClickListener() {
            @Override/*from  w w  w  .j  av a 2s. c  om*/
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ArticleActivity.class);
                if (resource.getReadURL() != null) {
                    intent.putExtra("url", resource.getReadURL());
                    intent.putExtra("verse", resource.getResourceVerse());
                    startActivity(intent);
                }

                mQuickAction.dismiss();
            }
        });
        mQuickAction.addActionItem(readAction);
    }

    //Check the links are actually there
    if (resource.getAudioURL() != null) {
        downloadAction.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                final String RESOURCE_FOLDER = "/CrossConnectAudio/";
                Toast.makeText(getActivity(), "Downloading Audio for " + resource.getResourceName(),
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Downloading Audio " + mAdapter.getItem(position).getResourceName() + "from "
                        + mAdapter.getItem(position).getAudioURL());

                Request request = new Request(Uri.parse(resource.getAudioURL()));
                File path = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS)
                                + RESOURCE_FOLDER);
                path.mkdir();

                String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS)
                        + RESOURCE_FOLDER + FileUtil.getFileName(mAdapter.getItem(position), bibleText);

                resourceService.insertUpdate(mAdapter.getItem(position), filePath, bibleText);

                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PODCASTS,
                        RESOURCE_FOLDER + FileUtil.getFileName(mAdapter.getItem(position), bibleText));

                enqueue = dm.enqueue(request);

                mQuickAction.dismiss();
            }
        });
        mQuickAction.addActionItem(downloadAction);

        playAction.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Streaming Audio for " + resource.getResourceName(),
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Streaming Audio" + mAdapter.getItem(position).getResourceName() + "from "
                        + mAdapter.getItem(position).getAudioURL());
                try {
                    // the download happens in another thread
                    Intent i = new Intent(MusicService.ACTION_URL);
                    Uri uri = Uri.parse(mAdapter.getItem(position).getAudioURL());
                    i.setData(uri);
                    getActivity().startService(i);

                } catch (Exception e) {
                    Log.d("BookManagerActivity", "Error on attempt to download", e);
                }

                mQuickAction.dismiss();
            }
        });

        mQuickAction.addActionItem(playAction);
    }

    mQuickAction.setAnimStyle(QuickActionVertical.ANIM_AUTO);

    mQuickAction.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss() {
        }
    });

    mQuickAction.show();
}

From source file:com.poinsart.votar.VotarMain.java

/** Create a File for saving an image or video */
@SuppressLint("SimpleDateFormat")
private 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_PICTURES), "VotAR");
    // 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.w("VotAR camera", "failed to create directory");
            return null;
        }//from  w  w w .j  ava  2  s .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 + ".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:com.renard.ocr.BaseDocumentActivitiy.java

protected void startCamera() {
    try {/*from   w  w w .  j a  v  a2s. c  o m*/
        cameraPicUri = null;
        dateCameraIntentStarted = new Date();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 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 image = null;
        try {
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            image = new File(storageDir, imageFileName + ".jpg");
            if (image.exists()) {
                image.createNewFile();
            }
            cameraPicUri = Uri.fromFile(image);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri);
            startActivityForResult(intent, REQUEST_CODE_MAKE_PHOTO);
        } catch (IOException e) {
            showFileError(PixLoadStatus.IO_ERROR);
        }

    } catch (ActivityNotFoundException e) {
        showFileError(PixLoadStatus.CAMERA_APP_NOT_FOUND);
    }
}

From source file:org.alfresco.mobile.android.application.fragments.fileexplorer.FileExplorerMenuFragment.java

private File requestWriteExternalStorage(final String externalFolder) {
    try {//from www  .j  a  v  a2 s  .c o  m
        if (Build.VERSION.SDK_INT < 23) {
            return (externalFolder == null) ? Environment.getExternalStorageDirectory()
                    : Environment.getExternalStoragePublicDirectory(externalFolder);
        }

        int hasWriteExternalStoragePermission = ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                        externalFolder == null ? BaseActivity.REQUEST_PERMISSION_SD
                                : BaseActivity.REQUEST_PERMISSION_DL);
                return null;
            }
            ActivityCompat.requestPermissions(getActivity(),
                    new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    externalFolder == null ? BaseActivity.REQUEST_PERMISSION_SD
                            : BaseActivity.REQUEST_PERMISSION_DL);
            return null;
        } else {
            return (externalFolder == null) ? Environment.getExternalStorageDirectory()
                    : Environment.getExternalStoragePublicDirectory(externalFolder);
        }
    } catch (Exception e) {
        Log.d(FileExplorerMenuFragment.TAG, Log.getStackTraceString(e));
    }
    return null;
}

From source file:com.longle1.facedetection.MainActivity.java

public FaceDetect(MainActivity context) throws IOException {
    super(context);

    // Create a private directory and file
    File classifierFile = new File(context.getDir("cascade", Context.MODE_PRIVATE),
            "haarcascade_frontalface_alt.xml");
    FileOutputStream os = new FileOutputStream(classifierFile);
    // load cascade file from application resources
    InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt);
    // copy from is to os
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);/*  w w w .  j  a v a2 s .c  o  m*/
    }
    is.close();
    os.close();

    if (classifierFile == null || classifierFile.length() <= 0) {
        throw new IOException("Could not extract the classifier file from Java resource.");
    }

    // Preload the opencv_objdetect module to work around a known bug.
    Loader.load(opencv_objdetect.class);
    classifier = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
    classifierFile.delete();
    if (classifier.isNull()) {
        throw new IOException("Could not load the classifier file.");
    }
    storage = CvMemStorage.create();

    // Preload the module to work around a known bug in FFmpegFrameRecorder
    Loader.load(swresample.class);

    // Create looper for asyncHttp
    HandlerThread thread2 = new HandlerThread("AsyncHttpResponseHandler",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mAsyncHttpLooper = thread2.getLooper();
    thread2.start();

    // temp video file
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    filePath = folder.getAbsolutePath() + "/Camera/" + "tmp" + ".mp4";

    // Create location
    mLocationData = new LocationData(getContext());
}

From source file:uk.ac.ucl.excites.sapelli.collector.CollectorApp.java

/**
 * @return//from  w  w  w.  j a  va2 s  .  c o m
 * @throws FileStorageException
 */
private FileStorageProvider initialiseFileStorage() throws FileStorageException {
    File sapelliFolder = null;

    // Try to get Sapelli folder path from preferences:
    try {
        sapelliFolder = new File(preferences.getSapelliFolderPath());
    } catch (NullPointerException npe) {
    }

    // Did we get the folder path from preferences? ...
    if (sapelliFolder == null) { // No: first installation or reset

        // Find appropriate files dir (using application-specific folder, which is removed upon app uninstall!):
        File[] paths = DeviceControl.getExternalFilesDirs(this, null);
        if (paths != null && paths.length != 0) {
            // We count backwards because we prefer secondary external storage (which is likely to be on an SD card rather unremovable memory)
            for (int p = paths.length - 1; p >= 0; p--)
                if (isMountedReadableWritableDir(paths[p])) {
                    sapelliFolder = paths[p];
                    break;
                }
        }

        // Do we have a path?
        if (sapelliFolder != null)
            // Yes: store it in the preferences:
            preferences.setSapelliFolder(sapelliFolder.getAbsolutePath());
        else
            // No :-(
            throw new FileStorageUnavailableException();
    } else { // Yes, we got path from preferences, check if it is available ...
        if (!isMountedReadableWritableDir(sapelliFolder)) // (will also attempt to create the directory if it doesn't exist)
            // No :-(
            throw new FileStorageRemovedException(sapelliFolder.getAbsolutePath());
    }

    // If we get here this means we have a non-null sapelliFolder object representing an accessible path...

    // Try to get the Android Downloads folder...
    File downloadsFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (!isMountedReadableWritableDir(downloadsFolder)) // check if we can access it (will also attempt to create the directory if it doesn't exist)
        // No :-(
        throw new FileStorageException("Cannot access downloads folder: " + downloadsFolder.getAbsolutePath());

    // Return path provider
    return new AndroidFileStorageProvider(sapelliFolder, downloadsFolder); // Android specific subclass of FileStorageProvider, which generates .nomedia files
}

From source file:cn.xcom.helper.activity.AuthorizedActivity.java

private void showPickDialog() {
    new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
            .setNegativeButton("", new DialogInterface.OnClickListener() {
                @Override/*w w w.java2  s  .co m*/
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent albumIntent = new Intent();
                    albumIntent.setType("image/*");
                    albumIntent.setAction(Intent.ACTION_PICK);
                    startActivityForResult(albumIntent, PHOTO_REQUEST_ALBUM);
                }
            }).setPositiveButton("?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    int permissionCheck = ContextCompat.checkSelfPermission(mContext,
                            Manifest.permission.CAMERA);
                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        String state = Environment.getExternalStorageState();
                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                            File path = Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                            File file = new File(path, "51helper.jpg");
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        }
                        startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
                    } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext,
                                Manifest.permission.CAMERA)) {

                            // Show an expanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                        } else {

                            // No explanation needed, we can request the permission.

                            ActivityCompat.requestPermissions((Activity) mContext,
                                    new String[] { Manifest.permission.CAMERA },
                                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.
                        }
                    }

                }
            }).show();
}

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

private void startCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(new File(mediaStorageDir + File.separator + "tmpImg.jpg")));
    startActivityForResult(Intent.createChooser(intent, getString(R.string.feedback_capture)), 100);
}

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

private void takePhoto() {
    //?? ??/*from   w ww .  j a v a  2  s. c  o  m*/
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date(System.currentTimeMillis());
    String filename = format.format(date);
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File outputImage = new File(path, filename + ".jpg");
    try {
        if (outputImage.exists()) {
            outputImage.delete();
        }
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //File?Uri??
    if (Build.VERSION.SDK_INT < 24) {

        imageUri = Uri.fromFile(outputImage);
    } else {
        imageUri = FileProvider.getUriForFile(mActivity, "com.luoli.cameraalbumtest.fileprovider", outputImage);
    }
    Intent tTntent = new Intent("android.media.action.IMAGE_CAPTURE"); //
    tTntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //?
    startActivityForResult(tTntent, CAMERA); //?

}

From source file:com.mygaadi.imageselectorlibrary.camera2.Camera2BasicFragment.java

private static File getOutputMediaFile(int type) {

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

    if (Utility.checkForExternalDirectory(mediaStorageDir)) {
        return null;
    }/*from w w  w.j a  v a 2  s . co m*/

    // 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 + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}