如何将 Bundle 转换为 WorkManager 数据

How convert Bundle to WorkManager Data

我尝试在处理 GCM 时摆脱 IntentService,如所述 here. Because of Android O background limitation. But i can't pass Bundle extras with push info as parameter to WorkManager from BroadcastReceiver. Is there any way to put Bundle into WorkManager Data?

我用简单的方法解决了这个问题。我注意到,Bundle 的整个参数都是字符串,所以我只是将它们放入 broadcastReceiver 中的 Data 并在 Worker 中转换回来。

class GcmWorker : Worker() {
    companion object {
        fun createWork(extras: Bundle): OneTimeWorkRequest {
            val dataBuilder = Data.Builder()
            extras.keySet().forEach {
                dataBuilder.putString(it, extras.getString(it))
            }

            return OneTimeWorkRequest.Builder(GcmWorker::class.java)
                    .setInputData(dataBuilder.build())
                    .build()
        }
    }

    override fun doWork(): Result {
        val extras = Bundle()
        for (key in inputData.keyValueMap.keys) {
            extras.putString(key, value)
        }
        // ...
        return WorkResult.FAILURE
    }
}