Android How to Use Environment.Getexternalstoragedirectory()

Android how to use Environment.getExternalStorageDirectory()

Environment.getExternalStorageDirectory().getAbsolutePath()

Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.

Here's a simple example for writing a file:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();

Edit:

Oops - you wanted an example for reading ...

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);

byte[] bytes;

// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes);
fiStream.close();

Environment.getExternalStorageDirectory() deprecated in API level 29 java

Use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDirs() (methods on Context) instead of Environment.getExternalStorageDirectory().

Or, modify mPhotoEditor to be able to work with a Uri, then:

  • Use ACTION_CREATE_DOCUMENT to get a Uri to a location of the user's choosing, or

  • Use MediaStore, ContentResolver, and insert() to get a Uri for a particular type of media (e.g., an image) — see this sample app that demonstrates doing this for downloading MP4 videos from a Web site

Also, note that your Uri.fromFile with ACTION_MEDIA_SCANNER_SCAN_FILE should be crashing on Android 7.0+ with a FileUriExposedException. On Android Q, only the MediaStore/insert() option will get your content indexed by the MediaStore quickly.

Note that you can opt out of these "scoped storage" changes on Android 10 and 11, if your targetSdkVersion is below 30, using android:requestLegacyExternalStorage="true" in the <application> element of the manifest. This is not a long-term solution, as your targetSdkVersion will need to be 30 or higher sometime in 2021 if you are distributing your app through the Play Store (and perhaps elsewhere).

Accessing getExternalStorageDirectory

I have tried this logic in Marshmallow (6.0) :

  1. make sure you have this in your manifest :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


  1. when try to access external storage please check the permission before entering the logic to read directory :

    public void checkPermissionReadStorage(Activity activity){
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
    Manifest.permission.READ_EXTERNAL_STORAGE)) {

    // 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,
    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
    MY_PERMISSIONS_REQUEST_READ_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant. The callback method gets the
    // result of the request.
    }
    }
    }
  2. and then override this method in your activity :

    @Override
    public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {
    case PermissionManager.MY_PERMISSIONS_REQUEST_READ_STORAGE: {
    //premission to read storage
    if (grantResults.length > 0
    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

    // permission was granted, yay! Do the
    // contacts-related task you need to do.

    } else {

    // permission denied, boo! Disable the
    // functionality that depends on this permission.
    Toast.makeText(SnapSellAddActivity.this, "We Need permission Storage", Toast.LENGTH_SHORT).show();
    }
    return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
    }
    }
  3. after that you can finally read the external storage in android devices, I tried like this method to read directory in external storage :

    public File getPreviewTempExternalDirectory(Context context) {
    File previewDir = new File(context.getExternalFilesDir(null), PLACE YOUT DIR HERE);
    if (!previewDir.exists()) previewDir.mkdir();
    return previewDir;
    }

    and now you have the directory, you can list file or create file there. hope it helps.

android Environment.getExternalStorageDirectory().getPath()

sd folder name different in Some phones

In samsung phones, it is named external_sd , and your code will fail.

control+shift+o --> to add imports in eclipse,see this link

"/sdcard/" is replace with "Environment.getExternalStorageDirectory().getPath()" in your code

The problem was that you call a file called Environment.java itself, so Eclipse didn't give me the choice to import Environment change that one.



Related Topics



Leave a reply



Submit