最近,我正在尝试将我的应用程序从 SDK-29 迁移到 SDK-30。我最关心的一件事是范围存储。
我在官方文档中看到“在 Android 11(API 级别 30)及更高版本上,应用程序无法在外部存储上创建自己的应用程序特定目录”。
因此,我尝试在外部存储中创建自己的目录并向其中写入一个新文件。代码如下所示:
// creating new directory under external storage
val appDir = File(applicationContext.getExternalFilesDir(null), "play")
appDir.mkdir()
// writing new file under my own directory
val newFile = File(appDir.absolutePath, "test.jpg")
val outputStream = FileOutputStream(newFile)
val inputStream = resources.openRawResource(R.drawable.ic_launcher_foreground)
val data = byteArrayOf()
inputStream.read(data)
outputStream.write(data)
inputStream.close()
outputStream.close()
Run Code Online (Sandbox Code Playgroud)
我预计这段代码会崩溃,但它有效。我在给定路径中找到该文件。所以,我有点困惑那张纸条的含义。
Google“无法在外部存储上创建自己的应用程序特定目录”是什么意思?
我试图将类型转换器添加到我的实体中,但我发现它仅适用于数据库、dao 和实体范围,而不适用于实体字段范围。
例如:当我像这样在实体范围中添加类型转换器时,它工作正常。
@Entity(tableName = "chat_history")
@TypeConverters(ChatEntityConverter::class)
class ChatHistoryEntity (
@PrimaryKey
@NonNull
@ColumnInfo(name = "history_id") val HID: Long?,
@ColumnInfo(name = "history_name") var pairedName: String?,
@ColumnInfo(name = "history_last_message") var lastMessage: String?,
@ColumnInfo(name = "history_last_date")
var lastDate: Date?
)
Run Code Online (Sandbox Code Playgroud)
但是如果我将它移动到实体字段范围,它就无法编译。
@Entity(tableName = "chat_history")
class ChatHistoryEntity (
@PrimaryKey
@NonNull
@ColumnInfo(name = "history_id") val HID: Long?,
@ColumnInfo(name = "history_name") var pairedName: String?,
@ColumnInfo(name = "history_last_message") var lastMessage: String?,
@TypeConverters(ChatEntityConverter::class)
@ColumnInfo(name = "history_last_date")
var lastDate: Date?
)
Run Code Online (Sandbox Code Playgroud)
它显示这样的错误消息:
error: Cannot figure out how to save …
Run Code Online (Sandbox Code Playgroud)