獲取到file的對象之后,調用 createNewFile 方法嘗試在指定目錄下生成一個文件並往文件中寫入內容,同樣的方法之前在android9及以前版本都沒問題,在網上查找了之后基本都指向了權限問題。
后經查找網上蠻多介紹這個問題的,android Q對於文件讀寫引入了新特性,在這個版本中,READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE均受到了限制,無法再像之前的版本直接獲取到文件。如果希望恢復之前的權限邏輯,可以在manifest文件中設置:
android:requestLegacyExternalStorage="true"
即可解決(但不確定這種方法是不是臨時的方法,有可能后面谷歌會干掉這種方式也說不定)。
另外,還可以通過StorageManager的getPrimaryStorageVolume().createOpenDocumentTreeIntent()方法來進行操作,這個方法沒有辦法通過File類來操作文件,但是可以使用類似的DocumentFile
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,正常在指定目錄下生成了對應文件