Environment.getExternalStorageDirectory() is deprecated过时的替代方案

用新的Android SDK 29编译的时候,Studio提示Environment.getExternalStorageDirectory()过时了,要用Context#getExternalFilesDir代替,Android Q以后Environment.getExternalStorageDirectory()返回的路径可能无法直接访问,所以改成了Context#getExternalFilesDir

所以Environment.getExternalStorageDirectory()可以改成:

getExternalFilesDir(null);

得到的路径如下:

/storage/emulated/0/Android/data/yourPackageName/files

这个目录会在应用被卸载的时候删除,而且访问这个目录不需要动态申请STORAGE权限。

如果这个目录不存在,系统会自动帮你创建,看下源码:

Environment.getExternalStorageDirectory() is deprecated过时的替代方案_第1张图片

getExternalFilesDir的参数可以传以下几种:

String?: The type of files directory to return. May be null for the root of the files directory or one of the following constants for a subdirectory: android.os.Environment#DIRECTORY_MUSICandroid.os.Environment#DIRECTORY_PODCASTSandroid.os.Environment#DIRECTORY_RINGTONESandroid.os.Environment#DIRECTORY_ALARMSandroid.os.Environment#DIRECTORY_NOTIFICATIONSandroid.os.Environment#DIRECTORY_PICTURES, or android.os.Environment#DIRECTORY_MOVIES. This value may be null.

例如我们传一个

getExternalFilesDir(Environment.DIRECTORY_PICTURES);

得到的路径如下:

/storage/emulated/0/Android/data/yourPackageName/files/Pictures

 

 

 

 

 

你可能感兴趣的:(Android开发)