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:fr.tvbarthel.attempt.googlyzooapp.MainActivity.java

/**
 * Save screen capture into external storage
 *
 * @param screenBytes/*  w w  w.  j  a  v  a  2  s .co m*/
 * @return path of the file
 */
private Uri writeScreenBytesToExternalStorage(byte[] screenBytes) {
    try {
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_HH_ss");
        final String filePrefix = "screen_";
        final String fileSuffix = ".jpg";
        final String fileName = filePrefix + simpleDateFormat.format(new Date()) + fileSuffix;
        final File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                + File.separator + "GooglyZoo", fileName);
        if (!f.getParentFile().isDirectory()) {
            f.getParentFile().mkdirs();
        }
        f.createNewFile();
        final FileOutputStream fo = new FileOutputStream(f);
        fo.write(screenBytes);
        fo.close();
        return Uri.fromFile(f);
    } catch (IOException e) {
        Log.e(TAG, "error while saving screen", e);
        return null;
    }
}

From source file:jackpal.androidterm.TermPreferences.java

private void confirmWritePrefs() {
    File pathExternalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    String downloadDir = pathExternalPublicDir.getPath();
    final String filename = downloadDir + "/" + BuildConfig.APPLICATION_ID + ".xml";
    if (new File(filename).exists()) {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setIcon(android.R.drawable.ic_dialog_info);
        bld.setMessage(this.getString(R.string.prefs_write_confirm));
        bld.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();/*from  w w  w.  j a  v a2  s .com*/
                writePrefs(filename);
            }
        });
        bld.setNegativeButton(this.getString(android.R.string.no), null);
        bld.create().show();
    } else {
        writePrefs(filename);
        return;
    }
}

From source file:com.google.android.apps.forscience.whistlepunk.project.UpdateProjectFragment.java

private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

    // This file isn't really temporary and actually gets persisted in the users public
    // directory for the app. We store the path of this file and persist it in SQLite alongside
    // the project to retrieve it later.
    File imageFile = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );// www .  j  ava2s  .c  om
    return imageFile;
}

From source file:com.learnncode.mediachooser.activity.HomeScreenMediaChooser.java

private File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            MediaChooserConstants.folderName);
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }// w w  w. jav  a 2 s.c  o  m
    }

    // 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:com.nbplus.hybrid.BasicWebViewClient.java

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // for excel download
    if (isDocumentMimeType(url)) {
        Log.d(TAG, "This url is document mimetype = " + url);
        if (StorageUtils.isExternalStorageWritable()) {
            Uri source = Uri.parse(url);

            // Make a new request pointing to the mp3 url
            DownloadManager.Request request = new DownloadManager.Request(source);
            // Use the same file name for the destination
            File destinationFile = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    source.getLastPathSegment());
            request.setDestinationUri(Uri.fromFile(destinationFile));
            // Add it to the manager
            mDownloadManager.enqueue(request);
            Toast.makeText(mContext, R.string.downloads_requested, Toast.LENGTH_SHORT).show();
        } else {//  w w  w  .  j av  a  2  s .  co m
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setPositiveButton("?", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //closeWebApplication();
                }
            });
            builder.setMessage(R.string.downloads_path_check);
            builder.show();
        }
        return true;
    }

    if (url.startsWith("tel:")) {
        // phone call
        if (!PhoneState.hasPhoneCallAbility(mContext)) {
            Log.d(TAG, ">> This device has not phone call ability !!!");
            return true;
        }

        mContext.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
    } else if (url.startsWith("mailto:")) {
        url = url.replaceFirst("mailto:", "");
        url = url.trim();

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[] { url });

        mContext.startActivity(i);
    } else if (url.startsWith("geo:")) {
        Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        mContext.startActivity(searchAddress);
    } else {
        //  URL ??   ? ??? .
        dismissProgressDialog();
        loadWebUrl(url);
        showProgressDialog();
    }
    return true;
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );/*from w  w  w  .  j  ava  2  s .  c  o m*/
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static boolean loadLibsSetup(String apkName) {
    // The package data lib directory isn't placed in ld.so's
    // search path, so we have to manually load libraries that
    // libxul will depend on.  Not ideal.
    GeckoApp geckoApp = GeckoApp.mAppContext;
    GeckoProfile profile = geckoApp.getProfile();
    profile.moveProfilesToAppInstallLocation();

    try {/*from w  w w.  j  av  a  2  s  .  c om*/
        String[] dirs = GeckoApp.mAppContext.getPluginDirectories();
        StringBuffer pluginSearchPath = new StringBuffer();
        for (int i = 0; i < dirs.length; i++) {
            Log.i(LOGTAG, "dir: " + dirs[i]);
            pluginSearchPath.append(dirs[i]);
            pluginSearchPath.append(":");
        }
        GeckoAppShell.putenv("MOZ_PLUGIN_PATH=" + pluginSearchPath);
    } catch (Exception ex) {
        Log.i(LOGTAG, "exception getting plugin dirs", ex);
    }

    GeckoAppShell.putenv("HOME=" + profile.getFilesDir().getPath());
    GeckoAppShell.putenv("GRE_HOME=" + GeckoApp.sGREDir.getPath());
    Intent i = geckoApp.getIntent();
    String env = i.getStringExtra("env0");
    Log.i(LOGTAG, "env0: " + env);
    for (int c = 1; env != null; c++) {
        GeckoAppShell.putenv(env);
        env = i.getStringExtra("env" + c);
        Log.i(LOGTAG, "env" + c + ": " + env);
    }

    File f = geckoApp.getDir("tmp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);

    if (!f.exists())
        f.mkdirs();

    GeckoAppShell.putenv("TMPDIR=" + f.getPath());

    f = Environment.getDownloadCacheDirectory();
    GeckoAppShell.putenv("EXTERNAL_STORAGE=" + f.getPath());

    File cacheFile = getCacheDir();
    String linkerCache = System.getenv("MOZ_LINKER_CACHE");
    if (System.getenv("MOZ_LINKER_CACHE") == null) {
        GeckoAppShell.putenv("MOZ_LINKER_CACHE=" + cacheFile.getPath());
    }

    File pluginDataDir = GeckoApp.mAppContext.getDir("plugins", 0);
    GeckoAppShell.putenv("ANDROID_PLUGIN_DATADIR=" + pluginDataDir.getPath());

    // gingerbread introduces File.getUsableSpace(). We should use that.
    long freeSpace = getFreeSpace();
    try {
        File downloadDir = null;
        File updatesDir = null;
        if (Build.VERSION.SDK_INT >= 8) {
            downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            updatesDir = GeckoApp.mAppContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        } else {
            updatesDir = downloadDir = new File(Environment.getExternalStorageDirectory().getPath(),
                    "download");
        }
        GeckoAppShell.putenv("DOWNLOADS_DIRECTORY=" + downloadDir.getPath());
        GeckoAppShell.putenv("UPDATES_DIRECTORY=" + updatesDir.getPath());
    } catch (Exception e) {
        Log.i(LOGTAG, "No download directory has been found: " + e);
    }

    putLocaleEnv();

    boolean extractLibs = GeckoApp.ACTION_DEBUG.equals(i.getAction());
    if (!extractLibs) {
        // remove any previously extracted libs
        File[] files = cacheFile.listFiles();
        if (files != null) {
            Iterator<File> cacheFiles = Arrays.asList(files).iterator();
            while (cacheFiles.hasNext()) {
                File libFile = cacheFiles.next();
                if (libFile.getName().endsWith(".so"))
                    libFile.delete();
            }
        }
    }
    return extractLibs;
}

From source file:com.dycode.jepretstory.mediachooser.activity.BucketHomeFragmentActivity.java

/** Create a File for saving an image or video */
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;
        }/* www. j  a  v a  2  s  .c  om*/
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).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:io.github.silencio_app.silencio.MainActivity.java

public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory.
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
            albumName);//from   w  w  w .ja  v  a2  s . c o  m
    if (!file.mkdirs()) {
        file.mkdirs();
    }
    return file;
}

From source file:com.dvdprime.mobile.android.ui.DocumentViewActivity.java

@Override
public boolean onContextItemSelected(android.view.MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    default://from   w w  w.j  av a 2 s  . c o m
    case CONTEXT_MENU_COPY_URL:
        SystemUtil.copyToClipboard(mActivity, contextUrl);
        break;
    case CONTEXT_MENU_BROWSER:
        AndroidUtil.clickedLinkAction(mActivity, contextUrl);
        break;
    case CONTEXT_MENU_SHARE_LINK:
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("text/plain");
        localIntent.putExtra("android.intent.extra.TEXT", contextUrl);
        startActivity(Intent.createChooser(localIntent, getString(R.string.action_bar_share_with)));
        break;
    case CONTEXT_MENU_SAVE_IMAGE:
        DownloadManager dm = (DownloadManager) getSystemService("download");
        DownloadManager.Request req = new DownloadManager.Request(Uri.parse(this.contextUrl));
        req.setTitle("DP Downloader");
        req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                StringUtil.substringAfterLast(this.contextUrl, "/"));
        req.setAllowedNetworkTypes(DownloadManager.PAUSED_QUEUED_FOR_WIFI);
        req.setMimeType("image/" + StringUtil.substringAfterLast(contextUrl, "."));
        File localFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (!(localFile.exists()))
            localFile.mkdirs();
        dm.enqueue(req);
        break;
    }

    return false;
}