使用 WorkManager 上传大型位图

Uploading large bitmaps using WorkManager

我正在尝试使用 WorkManager 将位图上传到服务器。基本上,用户拍照并按下按钮将其上传到服务器。

但是,当我尝试使用 Work Manager 的 Data.Builder class 序列化位图时,问题就来了,它有 10240 字节的限制。因此,如果我执行以下操作:

val data = Data.Builder()
//Add parameter in Data class. just like bundle. You can also add Boolean and Number in parameter.
data.putString(IMAGE_NAME, identifier)
data.putByteArray(BITMAP_ARRAY, imageBytes) 

会抛出以下崩溃java.lang.IllegalStateException: Data cannot occupy more than 10240 bytes when serialized

我总是可以在启动工作管理器之前将照片保存到文件中,然后在工作管理器中读取该文件。但是,如果可能的话,我宁愿避免所有文件管理,因为用户总是可以关闭应用程序等。

我只是想保存文件,如果服务器响应成功的话。

还有其他方法可以实现吗?这种东西有google"suggestion"吗?

这是我的 doWork() WorkManager 功能

    override fun doWork(): Result {
        val identifier = inputData.getString(IMAGE_NAME)!!
        val imageBytes = inputData.getByteArray(BITMAP_ARRAY)!!

        val result = executeRequest(identifier, imageBytes)

        return if (result.isSuccess()) {
            //saving image
            val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
            saveToInternalStorage(context, identifier, bitmap)
            Result.success()
        } else {
            Result.failure()
        }
    }

I would rathe avoid all file management if possible, because the user could always close the app, etc.

那么你不应该使用 WorkManager。 documentation 明确指出:

WorkManager is not intended for in-process background work that can safely be terminated if the app process goes away

关于将大量数据放入Datadocumentation对此也很清楚:

There is a maximum size limit of 10KB for Data objects. [...] If you need to pass more data in and out of your Worker, you should put your data elsewhere

所以如果你想为此使用 WorkManager(这对我来说是个好主意),你必须将大位图放在一个文件中,将该文件的 URI 放在 Data 对象,然后在您的 doWork() 中从该文件上传位图,然后删除该文件。

如果您在 doWork() 中间终止您的应用程序,WorkManager 框架将稍后启动您的应用程序进程(没有 UI)(退避时间增加)并且尝试再次上传。

我将图像保存到文件系统,然后在我的数据对象中传递了文件路径。在我的工作人员 class 中,我通过使用创建数据对象时传递的文件路径检索图像来上传图像