Search code examples
javaandroidandroid-storage

How to make Environment.getExternalStoragePublicDirectory() create a path to SD card, not to emulated/0 which is internal memory?


I creating a folder and putting a file in that folder using Environment.getExternalStoragePublicDirectory(). But it's creating a folder path to a place called /storage/emulated/0. I searched on the SD card for my file name, but there was any. So I determined that /storage/emulated/0 is a placed in the phone's internal memory. But according to Android Doc, external memory means SD card.

For example, screenshots are stored on the SD card and I can find it by going to the Android "Download" App->SD card->Pictures->Screenshots:

enter image description here.

Here are my code, the way I am creating a folder path and then create a unique file path for individual photo by appending the time at which the photo is stored:

public File getPublicDir() {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM),"collage");
if (!file.mkdirs()) {
    Log.e("PUBLIC DIRECTORY", "Directory not created");
}
return file;
}

try{
Calendar calendar= Calendar.getInstance();
SimpleDateFormat sdformat=new SimpleDateFormat("MM_dd_yyyy_HH:mm:ss");
String DateString=sdformat.format(calendar.getTime());
file=new File(getPublicDir(),"mySnapshot_"+DateString+".png");
FileOutputStream fos=new FileOutputStream(file);
Boolean success=snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Toast.makeText(MainActivity.this,"Compress? 
  :"+file,Toast.LENGTH_SHORT).show();
}catch(IOException e){
  e.printStackTrace();
  Toast.makeText(MainActivity.this,"NOT SAVED",Toast.LENGTH_SHORT).show();
}

EDIT:

I try String secStore = System.getenv("SECONDARY_STORAGE"); but secStore is null when I run the app. This is from this Stack answer.

I try manually typed in the folder address that leads to the SD card (in the picture above):

String dir="/document/3464-6161:collage";
file=new File(dir,"mySnapshot_"+DateString+".png");

But it gives me this error:

enter image description here


Solution

  • You can access external SD card by using getExternalStorageDirectory() and providing Request permission for Manifest.permission.WRITE_EXTERNAL_STORAGE

    Alternatively, you can use StorageManager.getStorageVolumes() to know what are the available volumes available in the device. It will return information about StorageVolume like SD card and USB.

    Note: it's available from API 24.

    Using this you can access the file path you need.