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.ywesee.amiko.MainActivity.java

/**
 * Takes screenshot of the whole screen/*  w ww.  j  a  v a 2  s  . c  o  m*/
 * @param activity
 */
public void sendFeedbackScreenshot(final Activity activity, int mode) {
    try {
        // Get root windows
        final View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content)
                .getRootView();
        rootView.setDrawingCacheEnabled(true);
        Bitmap bitmap = rootView.getDrawingCache();
        // The file be saved to the download folder
        File outputFile = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        + "/amiko_screenshot.png");
        FileOutputStream fOutStream = new FileOutputStream(outputFile);
        // Picture is then compressed
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
        rootView.setDrawingCacheEnabled(false);
        fOutStream.close();
        // Start email activity
        if (mode == 1)
            startEmailActivity(activity, Uri.fromFile(outputFile), "", "AmiKo for Android");
        else if (mode == 2)
            startEmailActivity(activity, Uri.fromFile(outputFile), "zdavatz@ywesee.com",
                    "Interaction notification");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Copy a file into a dstPath directory.
 * The output filename can be provided./* w w  w  . jav  a2s .c o  m*/
 * The output file is not overridden if it is already exist.
 *
 * @param sourceFile     the file source path
 * @param dstDirPath     the dst path
 * @param outputFilename optional the output filename
 * @return the downloads file path if the file exists or has been properly saved
 */
private static String saveFileInto(File sourceFile, String dstDirPath, String outputFilename) {
    // sanity check
    if ((null == sourceFile) || (null == dstDirPath)) {
        return null;
    }

    // defines another name for the external media
    String dstFileName;

    // build a filename is not provided
    if (null == outputFilename) {
        // extract the file extension from the uri
        int dotPos = sourceFile.getName().lastIndexOf(".");

        String fileExt = "";
        if (dotPos > 0) {
            fileExt = sourceFile.getName().substring(dotPos);
        }

        dstFileName = "vector_" + System.currentTimeMillis() + fileExt;
    } else {
        dstFileName = outputFilename;
    }

    File dstDir = Environment.getExternalStoragePublicDirectory(dstDirPath);
    if (dstDir != null) {
        dstDir.mkdirs();
    }

    File dstFile = new File(dstDir, dstFileName);

    // if the file already exists, append a marker
    if (dstFile.exists()) {
        String baseFileName = dstFileName;
        String fileExt = "";

        int lastDotPos = dstFileName.lastIndexOf(".");

        if (lastDotPos > 0) {
            baseFileName = dstFileName.substring(0, lastDotPos);
            fileExt = dstFileName.substring(lastDotPos);
        }

        int counter = 1;

        while (dstFile.exists()) {
            dstFile = new File(dstDir, baseFileName + "(" + counter + ")" + fileExt);
            counter++;
        }
    }

    // Copy source file to destination
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        dstFile.createNewFile();

        inputStream = new FileInputStream(sourceFile);
        outputStream = new FileOutputStream(dstFile);

        byte[] buffer = new byte[1024 * 10];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
    } catch (Exception e) {
        dstFile = null;
    } finally {
        // Close resources
        try {
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
        } catch (Exception e) {
            Log.e(LOG_TAG, "## saveFileInto(): Exception Msg=" + e.getMessage());
        }
    }

    if (null != dstFile) {
        return dstFile.getAbsolutePath();
    } else {
        return null;
    }
}

From source file:com.almalence.opencam.SavingService.java

public static File getSaveDir(boolean forceSaveToInternalMemory) {
    File dcimDir, saveDir = null, memcardDir;
    boolean usePhoneMem = true;

    String abcDir = "Camera";
    if (sortByData) {
        Calendar rightNow = Calendar.getInstance();
        abcDir = String.format("%tF", rightNow);
    }/*from  w ww . ja v a  2s.  co m*/

    if (Integer.parseInt(saveToPreference) == 1) {
        dcimDir = Environment.getExternalStorageDirectory();

        for (int i = 0; i < SAVEDIR_DIR_PATH_NAMES.length; i++) {
            if (MEMCARD_DIR_PATH[i].isEmpty()) {
                memcardDir = new File(dcimDir, MEMCARD_DIR_PATH_NAMES[i]);
                if (memcardDir.exists()) {
                    saveDir = new File(dcimDir, SAVEDIR_DIR_PATH_NAMES[i] + abcDir);
                    usePhoneMem = false;
                    break;
                }
            } else {
                memcardDir = new File(MEMCARD_DIR_PATH[i], MEMCARD_DIR_PATH_NAMES[i]);
                if (memcardDir.exists()) {
                    saveDir = new File(MEMCARD_DIR_PATH[i], SAVEDIR_DIR_PATH_NAMES[i] + abcDir);
                    usePhoneMem = false;
                    break;
                }
            }
        }
    } else if ((Integer.parseInt(saveToPreference) == 2)) {
        if (sortByData) {
            saveDir = new File(saveToPath, abcDir);
        } else {
            saveDir = new File(saveToPath);
        }
        usePhoneMem = false;
    }

    if (usePhoneMem || forceSaveToInternalMemory) // phone memory (internal
    // sd card)
    {
        dcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        saveDir = new File(dcimDir, abcDir);
    }
    if (!saveDir.exists())
        saveDir.mkdirs();

    // if creation failed - try to switch to phone mem
    if (!saveDir.exists()) {
        dcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        saveDir = new File(dcimDir, abcDir);

        if (!saveDir.exists())
            saveDir.mkdirs();
    }
    return saveDir;
}

From source file:com.gelakinetic.mtgfam.fragments.CardViewFragment.java

/**
 * Returns the File used to save this card's image
 *
 * @param shouldDelete true if the file should be deleted before returned, false otherwise
 * @return A File, either with the image already or blank
 * @throws Exception If something goes wrong
 *///from w w  w.  ja v a2s.c  o m
private File getSavedImageFile(boolean shouldDelete) throws Exception {

    String strPath;
    try {
        strPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getCanonicalPath()
                + "/MTGFamiliar";
    } catch (IOException ex) {
        throw new Exception(getString(R.string.card_view_no_pictures_folder));
    }

    File fPath = new File(strPath);

    if (!fPath.exists()) {
        if (!fPath.mkdir()) {
            throw new Exception(getString(R.string.card_view_unable_to_create_dir));
        }

        if (!fPath.isDirectory()) {
            throw new Exception(getString(R.string.card_view_unable_to_create_dir));
        }
    }

    fPath = new File(strPath, mCardName + "_" + mSetCode + ".jpg");

    if (shouldDelete) {
        if (fPath.exists()) {
            if (!fPath.delete()) {
                throw new Exception(getString(R.string.card_view_unable_to_create_file));
            }
        }
    }

    return fPath;
}

From source file:com.almalence.opencam.SavingService.java

@TargetApi(19)
public static DocumentFile getSaveDirNew(boolean forceSaveToInternalMemory) {
    DocumentFile saveDir = null;/*from w w w . j a va2s  .  c o m*/
    boolean usePhoneMem = true;

    String abcDir = "Camera";
    if (sortByData) {
        Calendar rightNow = Calendar.getInstance();
        abcDir = String.format("%tF", rightNow);
    }

    int saveToValue = Integer.parseInt(saveToPreference);
    if (saveToValue == 1 || saveToValue == 2) {
        boolean canWrite = false;
        String uri = saveToPath;
        try {
            saveDir = DocumentFile.fromTreeUri(ApplicationScreen.instance, Uri.parse(uri));
        } catch (Exception e) {
            saveDir = null;
        }
        List<UriPermission> perms = ApplicationScreen.instance.getContentResolver()
                .getPersistedUriPermissions();
        for (UriPermission p : perms) {
            if (p.getUri().toString().equals(uri.toString()) && p.isWritePermission()) {
                canWrite = true;
                break;
            }
        }

        if (saveDir != null && canWrite && saveDir.exists()) {
            if (sortByData) {
                DocumentFile dateFolder = saveDir.findFile(abcDir);
                if (dateFolder == null) {
                    dateFolder = saveDir.createDirectory(abcDir);
                }
                saveDir = dateFolder;
            }
            usePhoneMem = false;
        }
    }

    if (usePhoneMem || forceSaveToInternalMemory) // phone memory (internal
    // sd card)
    {
        saveDir = DocumentFile
                .fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
        DocumentFile abcFolder = saveDir.findFile(abcDir);
        if (abcFolder == null || !abcFolder.exists()) {
            abcFolder = saveDir.createDirectory(abcDir);
        }
        saveDir = abcFolder;
    }

    return saveDir;
}

From source file:com.ywesee.amiko.MainActivity.java

/**
 * Downloads and updates the SQLite database and the error report file
 *//*from   ww w . j  a  v  a 2  s .com*/
public void downloadUpdates() {
    // Signal that update is in progress
    mUpdateInProgress = true;
    mDownloadedFileCount = 0;

    // First check network connection
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    // Fetch data...
    if (networkInfo != null && networkInfo.isConnected()) {
        // File URIs
        Uri databaseUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedDatabase());
        Uri reportUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appReportFile());
        Uri interactionsUri = Uri.parse("http://pillbox.oddb.org/" + Constants.appZippedInteractionsFile());
        // NOTE: the default download destination is a shared volume where the system might delete your file if
        // it needs to reclaim space for system use
        DownloadManager.Request requestDatabase = new DownloadManager.Request(databaseUri);
        DownloadManager.Request requestReport = new DownloadManager.Request(reportUri);
        DownloadManager.Request requestInteractions = new DownloadManager.Request(interactionsUri);
        // Allow download only over WIFI and Mobile network
        requestDatabase.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestReport.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        requestInteractions.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
        // Download visible and shows in notifications while in progress and after completion
        requestDatabase.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestReport.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        requestInteractions
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // Set the title of this download, to be displayed in notifications (if enabled).
        requestDatabase.setTitle("AmiKo SQLite database update");
        requestReport.setTitle("AmiKo report update");
        requestInteractions.setTitle("AmiKo drug interactions update");
        // Set a description of this download, to be displayed in notifications (if enabled)
        requestDatabase.setDescription("Updating the AmiKo database.");
        requestReport.setDescription("Updating the AmiKo error report.");
        requestInteractions.setDescription("Updating the AmiKo drug interactions.");
        // Set local destination to standard directory (place where files downloaded by the user are placed)
        /*
        String main_expansion_file_path = Utilities.expansionFileDir(getPackageName());
        requestDatabase.setDestinationInExternalPublicDir(main_expansion_file_path, Constants.appZippedDatabase());
        */
        requestDatabase.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedDatabase());
        requestReport.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appReportFile());
        requestInteractions.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                Constants.appZippedInteractionsFile());
        // Check if file exist on non persistent store. If yes, delete it.
        if (Utilities.isExternalStorageReadable() && Utilities.isExternalStorageWritable()) {
            Utilities.deleteFile(Constants.appZippedDatabase(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appReportFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            Utilities.deleteFile(Constants.appZippedInteractionsFile(),
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        }
        // The downloadId is unique across the system. It is used to make future calls related to this download.
        mDatabaseId = mDownloadManager.enqueue(requestDatabase);
        mReportId = mDownloadManager.enqueue(requestReport);
        mInteractionsId = mDownloadManager.enqueue(requestInteractions);

        mProgressBar = new ProgressDialog(MainActivity.this);
        mProgressBar.setMessage("Downloading SQLite database...");
        mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressBar.setProgress(0);
        mProgressBar.setMax(100);
        mProgressBar.setCancelable(false);
        mProgressBar.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean downloading = true;
                while (downloading) {
                    DownloadManager.Query q = new DownloadManager.Query();
                    q.setFilterById(mDatabaseId);
                    Cursor cursor = mDownloadManager.query(q);
                    cursor.moveToFirst();
                    int bytes_downloaded = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor
                            .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    if (cursor.getInt(cursor.getColumnIndex(
                            DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        if (mProgressBar.isShowing())
                            mProgressBar.dismiss();
                    }
                    final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setProgress((int) dl_progress);
                        }
                    });
                    cursor.close();
                }
            }
        }).start();
    } else {
        // Display error report
    }
}

From source file:ac.robinson.mediaphone.MediaPhoneActivity.java

protected BackgroundRunnable getMediaLibraryAdderRunnable(final String mediaPath,
        final String outputDirectoryType) {
    return new BackgroundRunnable() {
        @Override/*ww w .  j av  a  2  s .c o  m*/
        public int getTaskId() {
            return 0;
        }

        @Override
        public boolean getShowDialog() {
            return false;
        }

        @Override
        public void run() {
            if (IOUtilities.externalStorageIsWritable()) {
                File outputDirectory = Environment.getExternalStoragePublicDirectory(outputDirectoryType);
                try {
                    outputDirectory.mkdirs();
                    File mediaFile = new File(mediaPath);
                    // use current time as this happens at creation; newDatedFileName guarantees no collisions
                    File outputFile = IOUtilities.newDatedFileName(outputDirectory,
                            IOUtilities.getFileExtension(mediaFile.getName()));
                    IOUtilities.copyFile(mediaFile, outputFile);
                    MediaScannerConnection.scanFile(MediaPhoneActivity.this,
                            new String[] { outputFile.getAbsolutePath() }, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(String path, Uri uri) {
                                    if (MediaPhone.DEBUG)
                                        Log.d(DebugUtilities.getLogTag(this), "MediaScanner imported " + path);
                                }
                            });
                } catch (IOException e) {
                    if (MediaPhone.DEBUG)
                        Log.d(DebugUtilities.getLogTag(this), "Unable to save media to " + outputDirectory);
                }
            }
        }
    };
}