Android solves the problem of getExternalStorageDirectory being abandoned after 29 of recommendation

  • 2021-12-11 09:09:08
  • OfStack

Today, I'd like to share with you Android to solve the problem of getExternalStorageDirectory being abandoned after 29. It can be used by personal test, and friends who need it can eat it with confidence.

Original intention: After Android 10, I believe everyone has encountered the problem of abandonment of getExternalStorageDirectory. After reading the Internet, many of them have used getExternalFilesDir according to the official, but the notice after saving the pictures to the photo album has become a problem, so we should not take the wrong road and directly replace getExternalStorageDirectory

Needless to say, go directly to the code:


// SDCard Address  /storage/emulated/0
  // getExternalStorageDirectory In 29 Abandoned 
//  String saveDir = Environment.getExternalStorageDirectory().getAbsolutePath();
  // getExternalFilesDir()  Used to get SDCard/Android/data/ Package name of your application /files/  Directory 
  File externalFileRootDir = getExternalFilesDir(null);
  do {
   externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
  } while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));

  String saveDir = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
  String savePath = saveDir + "/" + Environment.DIRECTORY_DCIM + "/" + filename;

Finally, savePath is the photo album path in SDCard


Related articles: