在安卓Q(10)上操做文件读写时遇到的问题,进行记录。

获取到file的对象以后,调用 createNewFile 方法尝试在指定目录下生成一个文件并往文件中写入内容,一样的方法以前在android9及之前版本都没问题,在网上查找了以后基本都指向了权限问题。android

后经查找网上蛮多介绍这个问题的,android Q对于文件读写引入了新特性,在这个版本中,READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE均受到了限制,没法再像以前的版本直接获取到文件。若是但愿恢复以前的权限逻辑,能够在manifest文件中设置:app

android:requestLegacyExternalStorage="true"
便可解决(但不肯定这种方法是否是临时的方法,有可能后面谷歌会干掉这种方式也说不定)。ui

另外,还能够经过StorageManager的getPrimaryStorageVolume().createOpenDocumentTreeIntent()方法来进行操做,这个方法没有办法经过File类来操做文件,可是可使用相似的DocumentFilespa

1 <application 2         android:sharedUserId="android.uid.system"
3         android:allowBackup="true"
4         android:icon="@mipmap/ic_launcher"
5         android:label="@string/app_name"
6         android:roundIcon="@mipmap/ic_launcher_round"
7         android:supportsRtl="true"
8         android:requestLegacyExternalStorage="true"
9         android:theme="@style/AppTheme">

而后从新编译apk,安装打开apk,正常在指定目录下生成了对应文件code

相关文章
相关标签/搜索