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.giovanniterlingen.windesheim.view.DownloadsActivity.java

private void updateFilesList() {
    final File path = Environment.getExternalStoragePublicDirectory(
            ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
    File files[] = path.listFiles();
    if (files != null && files.length > 0) {
        List<NatschoolContent> contents = new ArrayList<>();
        for (File f : files) {
            if (!f.isDirectory()) {
                contents.add(new NatschoolContent(f.getName()));
            }// ww w. j ava  2  s. c  o  m
        }
        if (contents.size() == 0) {
            showEmptyTextview();
        } else {
            hideEmptyTextview();
        }
        if (recyclerView == null) {
            recyclerView = findViewById(R.id.downloads_recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        }
        recyclerView.setAdapter(new NatschoolContentAdapter(this, contents) {
            @Override
            protected void onContentClick(NatschoolContent content, int position) {
                Uri uri;
                File file = new File(path.getAbsolutePath() + File.separator + content.name);
                Intent target = new Intent(Intent.ACTION_VIEW);
                if (android.os.Build.VERSION.SDK_INT >= 24) {
                    uri = FileProvider.getUriForFile(DownloadsActivity.this,
                            "com.giovanniterlingen.windesheim.provider", file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    uri = Uri.fromFile(file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                }
                String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
                String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                target.setDataAndType(uri, mimetype);

                try {
                    startActivity(target);
                } catch (ActivityNotFoundException e) {
                    if (view != null) {
                        Snackbar snackbar = Snackbar.make(view, getResources().getString(R.string.no_app_found),
                                Snackbar.LENGTH_SHORT);
                        snackbar.show();
                    }
                }
            }
        });
    } else {
        showEmptyTextview();
    }
}

From source file:com.xbm.android.matisse.internal.utils.MediaStoreCompat.java

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = String.format("JPEG_%s.jpg", timeStamp);
    File storageDir;//w w w.  j a  v  a2 s.c o m
    if (mCaptureStrategy.isPublic) {
        storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    } else {
        storageDir = mContext.get().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }

    // Avoid joining path components manually
    File tempFile = new File(storageDir, imageFileName);

    // Handle the situation that user's external storage is not ready
    if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
        return null;
    }

    return tempFile;
}

From source file:sg.fxl.topeka.widget.quiz.ImageQuizView.java

private File createImageFile() throws IOException {
    int permission = ActivityCompat.checkSelfPermission(getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission == PackageManager.PERMISSION_GRANTED) {
        // 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 = File.createTempFile(imageFileName, ".jpg", storageDir);
        // Save a file: path for use with ACTION_VIEW intents
        photoPath = "file://" + image.getPath();
        return image;
    } else {//from   w  w w.  j  av  a  2  s. co m
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions((Activity) getContext(), PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE);
        return null;
    }
}

From source file:com.esri.squadleader.controller.AdvancedSymbolController.java

/**
 * Copies the MIL-STD-2525C symbol dictionary from assets to the device's downloads directory if
 * it is not already there./* w ww .  j  a v  a 2s.com*/
 *
 * @param assetManager            the application's AssetManager, from which the advanced symbology database
 *                                will be copied.
 * @param symbolDictionaryDirname the name of the asset directory that contains the advanced symbology
 *                                database.
 * @return the symbol dictionary directory. This may be freshly copied or it might have already
 * been there.
 * @throws IOException if the symbol dictionary cannot be copied to disk.
 */
public static File copySymbolDictionaryToDisk(AssetManager assetManager, String symbolDictionaryDirname)
        throws IOException {
    File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (!downloadsDir.exists()) {
        downloadsDir.mkdirs();
    }
    File symDictDir = new File(downloadsDir, symbolDictionaryDirname);

    boolean copyNeeded = !symDictDir.exists();
    if (!copyNeeded) {
        /**
         * Check to see if we need to upgrade the symbol dictionary. One way is to
         * see if PositionReport.json's renderer is of type 2525C (10.2) or mil2525c (10.2.4).
         */
        StringBuilder sb = new StringBuilder();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(new File(symDictDir, "messagetypes/PositionReport.json")));
            String line;
            while (null != (line = in.readLine())) {
                sb.append(line);
            }
            JSONObject json = new JSONObject(sb.toString());
            if (!"mil2525c".equals(json.getJSONObject("renderer").getString("dictionaryType"))) {
                copyNeeded = true;
            }
        } catch (Exception e) {
            copyNeeded = true;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Throwable t) {
                    //Swallow
                }
            }
        }
    }
    if (copyNeeded) {
        symDictDir.delete();
        Utilities.copyAssetToDir(assetManager, symbolDictionaryDirname, downloadsDir.getAbsolutePath());
    }
    return symDictDir;
}

From source file:com.nichtemna.takeandsavephoto.PhotoFragment.java

/**
 * Gets list of files in this folder//from   w ww.  ja  va  2 s.com
 */
private void getFileList() {
    files.clear();
    File root = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES + "/" + getString(R.string.app_name));
    Collections.addAll(files, root.listFiles());
    Collections.sort(files, new CustomComparator());
    adapter = new ViewPagerAdapter(getActivity(), files);
    viewPager.setAdapter(adapter);

    imb_remove.setVisibility(files.size() > 0 ? View.VISIBLE : View.INVISIBLE);
}

From source file:com.maxwen.wallpaper.board.fragments.SettingsFragment.java

private void initSettings() {
    List<Setting> settings = new ArrayList<>();

    double cache = (double) FileHelper.getCacheSize(getActivity().getCacheDir()) / FileHelper.MB;
    NumberFormat formatter = new DecimalFormat("#0.00");

    settings.add(new Setting(R.drawable.ic_toolbar_storage,
            getActivity().getResources().getString(R.string.pref_data_header), "", "", "", Setting.Type.HEADER,
            -1));/* w  w w .ja v  a  2s  .  c  o  m*/

    settings.add(new Setting(-1, "", getActivity().getResources().getString(R.string.pref_data_cache),
            getActivity().getResources().getString(R.string.pref_data_cache_desc),
            String.format(getActivity().getResources().getString(R.string.pref_data_cache_size),
                    formatter.format(cache) + " MB"),
            Setting.Type.CACHE, -1));

    settings.add(new Setting(R.drawable.ic_toolbar_theme,
            getActivity().getResources().getString(R.string.pref_theme_header), "", "", "", Setting.Type.HEADER,
            -1));

    settings.add(new Setting(-1, "", getActivity().getResources().getString(R.string.pref_theme_dark),
            getActivity().getResources().getString(R.string.pref_theme_dark_desc), "", Setting.Type.THEME,
            Preferences.getPreferences(getActivity()).isDarkTheme() ? 1 : 0));

    settings.add(new Setting(R.drawable.ic_toolbar_wallpapers,
            getActivity().getResources().getString(R.string.pref_wallpaper_header), "", "", "",
            Setting.Type.HEADER, -1));

    String directory = "";
    if (Preferences.getPreferences(getActivity()).getWallsDirectory() == null) {
        directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/"
                + getActivity().getResources().getString(R.string.app_name)).getAbsolutePath();
    } else {
        directory = Preferences.getPreferences(getActivity()).getWallsDirectory() + File.separator;
    }

    settings.add(new Setting(-1, "", getActivity().getResources().getString(R.string.pref_wallpaper_location),
            directory, "", Setting.Type.WALLPAPER, -1));

    settings.add(new Setting(-1, "", getActivity().getResources().getString(R.string.wallpaper_scroll_enable),
            getActivity().getResources().getString(R.string.wallpaper_scroll_enable_desc), "",
            Setting.Type.SCROLL, Preferences.getPreferences(getActivity()).isScrollWallpaper() ? 1 : 0));

    mAdapter = new SettingsAdapter(getActivity(), this, settings);
    mRecyclerView.setAdapter(mAdapter);
}

From source file:com.tcity.android.ui.info.BuildArtifactsFragment.java

@Override
public void onDownloadClick(@NotNull BuildArtifact artifact) {
    //noinspection ResultOfMethodCallIgnored
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();

    DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(calculateArtifactRequest(artifact));
}

From source file:org.jraf.android.downloadandshareimage.app.downloadandshare.DownloadAndShareActivity.java

public File getTemporaryFile() throws IOException {
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    dir.mkdirs();// w  ww. j a  va 2 s .co  m
    String fileName = FileUtil.getValidFileName(mUrl);
    fileName = fileName.substring(0, Math.min(80, fileName.length()));
    File file = new File(dir, fileName);
    Log.d("file=" + file);
    if (file.exists())
        file.delete();
    return file;
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void BackupDatabase() {
    String loc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            + "/AndroidLocalTodoBackup.db";
    try {//from  w w w .j  a  v  a2 s. c o  m
        mDB.BackupDatabase(loc);
        String[] paths = { loc };
        MediaScannerConnection.scanFile(this, paths, null, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskListActivity.this);
        AlertDialog dlg = builder.setTitle("Success!").setMessage("Database backed up!").create();
        dlg.show();
    } catch (java.io.IOException e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskListActivity.this);
        AlertDialog dlg = builder.setTitle("File I/O error!").setMessage(e.getMessage()).create();
        dlg.show();
    }
}

From source file:de.stadtrallye.rallyesoft.model.pictures.PictureManager.java

public PictureManager(Context applicationContext, IDbProvider dbProvider) {
    context = applicationContext;//  w  w w.  j  a  v a2 s .c  o m
    this.dbProvider = dbProvider;

    deviceID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "rallye");
    // 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.e(THIS, "failed to create directory");
            //            throw new UnsupportedOperationException("Failed to create directory");
        }
    }

    reload();
}