简体   繁体   中英

Method getExternalStorageDirectory() deprecated

I need to read an audio file recorded from the microphone of the smartphone, and for that I'm using the code below:

 pathSave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+ UUID.randomUUID().toString()+"audio_record.3gp";

The problem is that the method getExternalStorageDirectory() is deprecated at Android Studio (I'm using the version 3.5.3 and I didn´t indicated my API level).

There is another method that substitutes the getExternalStorageDirectory(), in other to not change my code so much.

Thank You.

I use the method below instead of Environment.getExternalStorageDirectory()

 String getRootDir() {
        return ctx.getExternalFilesDir(null).getParent().split("/Andro")[0];
 }

Android Studio version is irrelevant. Depreciation is at the SDK level. Docs say :

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 . Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

If you are not targeting Q you can ignore this for a while as depreciation means you should stop using the method, not that it stopped working as of sudden.

and I didn´t indicated my API level)

That's not true.

Environment.getExternalStorageDirectory()

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. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT .

For sample below code is older one. (deprecated)

val storageDir = File(Environment.getExternalStorageDirectory(), "pics")
storageDir.mkdirs()

We can use Context method as follows

val storageDir = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "pics")
storageDir.mkdirs()

please check the following link more details

Environment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM