Environment.getExternalStorageDirectory() deprecated in API level 29 java

environment.getexternalstoragedirectory() is deprecated
environment.getexternalstoragedirectory() not working
getexternalstoragedirectory replacement
getexternalfilesdir example
environment.getexternalstoragedirectory() not working in android 10
environment.getexternalstoragedirectory() alternative
android getexternalstoragepublicdirectory deprecated

Working on android Java, recently updated SDK to API level 29 now there is a warning shown which states that

Environment.getExternalStorageDirectory() is deprecated in API level 29

My code is

private void saveImage() {

if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

    final String folderPath = Environment.getExternalStorageDirectory() + "/PhotoEditors";
    File folder = new File(folderPath);
    if (!folder.exists()) {
        File wallpaperDirectory = new File(folderPath);

    final String filepath=folderPath
                + File.separator + ""
                + System.currentTimeMillis() + ".png";
    File file = new File(filepath);

    try {
        SaveSettings saveSettings = new SaveSettings.Builder()
        if(isStoragePermissionGranted() ) {
            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
            public void onSuccess(@NonNull String imagePath) {
                showSnackbar("Image Saved Successfully");
                mPhotoEditorView.getSource().setImageURI(Uri.fromFile(new File(imagePath)));
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(filepath))));
                Intent intent = new Intent(EditImageActivity.this, StartActivity.class);


            public void onFailure(@NonNull Exception exception) {
                showSnackbar("Failed to save Image");

What will be the alternative for this?

Environment, Provides access to environment variables. This method was deprecated in API level 29. This method was deprecated in API level 21. use getExternalStorageState(java.io. public static File getExternalStorageDirectory (). Environment.getExternalStorageDirectory() is deprecated in API level 29 My code is val wallpaperDirectory = File(Environment.getExternalStorageDirectory(), "NewFolder") wallpaperDirectory.mkdir()

Get the destPath with the new API call:

String destPath = mContext.getExternalFilesDir(null).getAbsolutePath();

Fix getExternalStorageDirectory is deprecated in API 29, Worried about finding a screenshot app ? USE CREATE SCREENSHOT APP Download now on Duration: 0:42 Posted: Jan 17, 2020 Environment.getExternalgetExternalStoragePublicDirectory(), Environment.getExternalStorageDirectory() is deprecated in Android Q Api Level 29

For Android Q, you can add android:requestLegacyExternalStorage="true" to your element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work.

<manifest ... >
<!-- This attribute is "false" by default on apps targeting
     Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >

Technically, you only need this once you update your targetSdkVersion to 29. Apps with lower targetSdkVersion values default to opting into legacy storage and would need android:requestLegacyExternalStorage="false" to opt out.

The Death of External Storage: The End of the Saga(?), If Q Beta 4 really does have the final APIs, then we may now have the final Without legacy storage, apps still can use getExternalFilesDir() and you only need this once you update your targetSdkVersion to 29 . getExternalStorageDirectory() or Environment. you will see that they are deprecated. getExtenalStoragePublicDirectory (String type) This method was deprecated in API level 29. To improve user privacy,direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps.

Please use getExternalFilesDir(), getExternalCacheDir() instead of Environment.getExternalStorageDirectory() when you creating file in Android 10.

See below line:

val file = File(this.externalCacheDir!!.absolutePath, "/your_file_name")

android.os.Environment.getDataDirectory java code examples , Environment.getExternalStorageDirectory() deprecated in API level 29 java. 11月. 17. 2019. By 时光毁灭记忆、已成空白. Working on android Java, recently� Environment.getExternalStorageDirectory() deprecated in API level,Use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDir() (​methods on Context) instead of Environment.getExternalStorageDirectory(). Working on android Java, recently updated SDK to API level 29 now there is a warning shown which states that.

This is a small example how to get URI for a file if you want to take photo using default camera and store it in a DCIM folder (DCIM/app_name/filename.jpg):

Open camera (remember about CAMERA permission):

private var photoURI: Uri? = null

private fun openCamera() {
    Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
        photoURI = getPhotoFileUri()
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
        takePictureIntent.resolveActivity(requireActivity().packageManager)?.also {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)

And get URI:

private fun getPhotoFileUri(): Uri {
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
    val fileName = "IMG_${timeStamp}.jpg"

    var uri: Uri? = null
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val resolver = requireContext().contentResolver
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
            put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/app_name/")

        uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

    return uri ?: getUriForPreQ(fileName)

private fun getUriForPreQ(fileName: String): Uri {
    val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
    val photoFile = File(dir, "/app_name/$fileName")
    if (photoFile.parentFile?.exists() == false) photoFile.parentFile?.mkdir()
    return FileProvider.getUriForFile(

Don't forget about WRITE_EXTERNAL_STORAGE permission for pre Q and add a FileProvider to AndroidManifest.xml.

And get a result:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
            photoURI?.let {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    val thumbnail: Bitmap =
                            it, Size(640, 480), null
                } else {
                    // pre Q actions

Storing Files in Internal & External Storage, private static CityDB openCityDB(Context context, String packageName) { String path = "/data" + Environment.getDataDirectory().getAbsolutePath() +� Icon Made for this Article. With the release of Android 10 (API level 29 or Q), a lot of things have changed in the Android SDK especially security-wise which is a good thing but being something that keeps evolving. there are always pros and cons to each evolutionary stage and it so happened that this time the cons were met with a lot of controversies by developers.

[path_provider] Migrate off getExternalStorageDirectory � Issue , File getExternalStorageDirectory () File getExternalFilesDir (String type) File getExternalStoragePublicDirectory (String type). In the beginning, everyone used Environment. Before API level 19, there was no official way to store in SD card. protected void onCreate(Bundle savedInstanceState) method of MainActivity. java If you will not be targeting Android 10 (API level 29), some of these changes might not immediately affect you. However, while you can currently use non-SDK interfaces that are part of the greylist (depending on your app's target API level), using any non-SDK method or field always carries a high risk of breaking your app.

android — Environment.getExternalStorageDirectory () en desuso , The deprecation notice: This method was deprecated in API level 29. To improve user privacy, direct access to shared/external storage devices is� To learn about the APIs, read the API diff report or visit the Android API reference — look for APIs that were "added in API level 29". Also be sure to check out Android 10 behavior changes (for apps targeting API level 29 and for all apps ), as well as privacy changes , to learn about areas where platform changes may affect your apps.

Android: mkdirs()/mkdir() on external storage returns false, Environment.getExternalStorageDirectory () en desuso en el nivel de API 29 java . Trabajando en Android Java, SDK actualizado recientemente al nivel API 29� Android External Storage: a place to store addition data of Android, the files that you store here is not applied the security system.

  • Dear @CommonsWare, should we ever meet in real live, please remind me that I owe you a beer for your blog post. I spent a whole afternoon finding out why a certain external library stopped working, as soon as I raised the targetSdk level to 29. Now I know why ...
  • @Commonsware can you provide example or appropriate code with usage of your answer?
  • using getExternalFilesDir() and getExternalCacheDir() can work with api 29 but when app unistalled all data will be removed using this methods ... If you use this attribute inside application tag "android:requestLegacyExternalStorage="true" " can work also for api 29 . When app unistalled file name exits but data removed
  • Hi , how can we use getExternalFilesDir() with custom path for save image , i want to use this for prevent show images into Gallery? In default it save to Andorid/data/packagename/...
  • @miladsalimi: Sorry, but I do not understand your question. I suggest that you ask a separate Stack Overflow question where you explain in detail what your concern is.
  • We can use this method: developer.android.com/training/data-storage/… ? What do you think about it ? :)
  • Can still get the environment variable getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) replaces Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
  • This post has saved my search for a solution of storing data on external storage in the latest version of Android Studio with an earlier developed code - which lasted 8 hours. Thank you.
  • Hi , how can we use getExternalFilesDir() with custom path for save image , i want to use this for prevent show images into Gallery? In default it save to Andorid/data/packagename/...
  • You will need to save the file to app directory and then insert this using Media uri
  • it is also deprecated
  • Duplicate of this comment: stackoverflow.com/a/61774820/7487335