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.indeema.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///w  w w  . ja  v a  2  s .  co  m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            if (attachment.mFileName == null) {
                // 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");
            }
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            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);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } 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.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        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 + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.kayzook.bracediary.BaseActivity.java

private File getOutputPhotoFile() {

    File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            getPackageName());//from   w w  w  .  j  a  v a2s  .  com

    if (!directory.exists()) {
        if (!directory.mkdirs()) {
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());

    return new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}

From source file:chinanurse.cn.nurse.Fragment_Nurse_job.IdentityFragment_ACTIVITY.java

protected void ShowPickDialog() {
    new AlertDialog.Builder(activity, AlertDialog.THEME_HOLO_LIGHT)
            .setNegativeButton("", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();/*from   ww  w.  j  a v a  2  s . c o  m*/
                    Intent intentFromGallery = new Intent();
                    intentFromGallery.setType("image/*"); // 
                    intentFromGallery.setAction(Intent.ACTION_PICK);
                    startActivityForResult(intentFromGallery, PHOTO_REQUEST_ALBUM);

                }
            }).setPositiveButton("?", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                    Intent intentFromCapture = 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, "newpic.jpg");
                        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    }

                    startActivityForResult(intentFromCapture, PHOTO_REQUEST_CAMERA);
                }
            }).show();
}

From source file:net.jongrakko.zipsuri.activity.PostReviseActivity.java

private void takeImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takeFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Zisuri_tmp_" + System.currentTimeMillis() + ".jpg");
    Uri saveUri = Uri.fromFile(takeFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // set the image file name
    startActivityForResult(intent, TAKE_PHOTO_FOR_AVATAR);
}

From source file:fpt.isc.nshreport.utilities.FileUtils.java

public static Uri createImageFile(Context context) throws IOException {
    // Create an image file name
    /*String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";*/
    String imageFileName = "JPEG_NSH.jpg";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "Camera");
    /*File image = File.createTempFile(
        imageFileName,  *//* prefix *//*
                                       ".jpg",         *//* suffix *//*
                                                                      storageDir      *//* directory *//*
                                                                                                        );*/

    File image = new File(storageDir, imageFileName);

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Uri photoURI = FileProvider.getUriForFile(context, "fpt.isc.nshreport.provider", image);
    return photoURI;
}

From source file:net.jongrakko.zipsuri.activity.PostReviseActivity.java

private void takeVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    takeFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Zisuri_tmp_" + System.currentTimeMillis() + ".mp4");
    Uri saveUri = Uri.fromFile(takeFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // set the image file name
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
    startActivityForResult(intent, TAKE_VIDEO_FOR_AVATAR);
}

From source file:com.adamas.client.android.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_scan_qr_code) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            IntentIntegrator integrator = new IntentIntegrator(this);
            integrator.initiateScan();//from  ww w.  j  av a2  s .  c om
        } else {
            checkCameraPermission();
        }
    } else if (id == R.id.action_delete_connector) {
        if (_connectorfragment != null) {
            _connectorfragment.deleteConnector(_selectedAdamasConnector);
        }
    } else if (id == R.id.action_add_connector_manually) {
        Intent intent = new Intent(this, AddConnectorActivity.class);
        startActivityForResult(intent, MANUALLY_ADD_CONNECTOR_REQUEST_CODE);
    } else if (id == R.id.action_edit_connector) {
        Intent intent = new Intent(this, EditConnectorActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(EditConnectorActivity.ADAMAS_CONNECTOR, _selectedAdamasConnector);
        intent.putExtras(mBundle);
        startActivityForResult(intent, MANUALLY_EDIT_CONNECTOR_REQUEST_CODE);
    } else if (id == R.id.action_import_connector_from_text) {
        Intent intent = new Intent(this, ImportTextActivity.class);
        startActivityForResult(intent, IMPORT_FROM_TEXT_REQUEST_CODE);
    } else if (id == R.id.action_import_connector_from_image) {
        if (false) {
            FileChooser fileChooser = new FileChooser(this);
            fileChooser.setFileListener(new FileChooser.FileSelectedListener() {
                @Override
                public void fileSelected(final File file) {
                    String name = file.getAbsolutePath();
                    name = name;
                }
            });
            fileChooser.showDialog();
        } else {
            // this is much better
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath());
            intent.setDataAndType(uri, "image/jpeg");
            startActivityForResult(Intent.createChooser(intent, getString(R.string.open)),
                    IMPORT_FROM_FILE_REQUEST_CODE);
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;/*from  w  w  w. ja  v a  2s  .  c  o  m*/

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}

From source file:net.jongrakko.zipsuri.fragment.MyPublicQuestionFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        File cropFile = new File(UCrop.getOutput(data).getPath());
        mAnswerModelPhoto.setImage0(cropFile.getAbsolutePath());
        ServerManager.uploadPublicAnswer(new ServerManager.OnServerListener<Void>() {
            @Override/*from w ww  . ja  v  a2s. c  o m*/
            protected void onSuccess(Void data) {
                getParentActivity().refreshData();
                ProgressManger.showToast("  !");
            }
        }, mAnswerModelPhoto);

    } else if (resultCode == Activity.RESULT_OK && requestCode == PICK_PHOTO_FOR_AVATAR) {
        UCrop.of(data.getData(),
                Uri.fromFile(
                        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                System.currentTimeMillis() + ".jpg")))
                .withMaxResultSize(1920, 1920).start(getContext(), this);
    } else if (resultCode == Activity.RESULT_OK && requestCode == TAKE_PHOTO_FOR_AVATAR) {
        UCrop.of(Uri.fromFile(takeFile),
                Uri.fromFile(
                        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                System.currentTimeMillis() + ".jpg")))
                .withMaxResultSize(1920, 1920).start(getContext(), this);
    } else if (resultCode == UCrop.RESULT_ERROR) {
        final Throwable cropError = UCrop.getError(data);
        Log.d("mox", "croperror" + cropError.toString());

    }
}