我正在为我的应用程序使用备份功能,其工作方式如下:Room db保存在app文件夹中的文件中(遵循新的Q准则,无需征求任何许可),并且文件本身立即共享备份后,以便用户可以将其保存或发送到某个地方。需要最后一步以避免丢失备份,因为在卸载应用程序后,备份就消失了,并且并非每个用户都会手动将其移动到其他位置。这是代码:
// Export the room database to a file in Android/data/com.minar.app/files
private fun exportDb(context: Context) {
// Perform a checkpoint to empty the write ahead logging temporary files and avoid closing the entire db
val eventDao = EventDatabase.getDataBase(context)!!.eventDao()
eventDao.checkpoint(SimpleSQLiteQuery("pragma wal_checkpoint(full)"))
val dbFile = context.getDatabasePath("appDB").absoluteFile
val appDirectory = File(context.getExternalFilesDir(null)!!.absolutePath)
val fileName: String = "appBackup_" + LocalDate.now()
val fileFullPath: String = appDirectory.path + File.separator.toString() + fileName
// Toasts need the ui thread to work, so they must be forced on that thread
try {
dbFile.copyTo(File(fileFullPath), true)
(context as MainActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.export_success), Toast.LENGTH_SHORT).show() }
}
catch (e: Exception) {
(context as MainActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.export_failure), Toast.LENGTH_SHORT).show() }
e.printStackTrace()
}
return fileFullPath
}
// Share the backup to a supported app
private fun shareBackup(fileUri: String) {
val shareIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, Uri.parse(fileUri))
type = "*/*"
}
// Verify that the intent will resolve to an activity
if (shareIntent.resolveActivity(context.packageManager) != null)
context.startActivity(shareIntent)
}
[我所做的就是在第二个函数中使用第一个函数的输出来调用这些函数,但是当我在某个位置(例如在Gmail上)共享文件时,我得到的只是“无法附加空文件”。备份工作正常,因为我可以在任何SQLite查看器中打开文件。所以我的问题如下:
尝试这个: