doWork()
工人类方法从未在Android中调用
我想在连接互联网时将脱机数据与服务器同步
//工人经理班级
class UploadWorker (context: Context, workerParameters: WorkerParameters, val authRepository: AuthRepository): Worker(context,workerParameters) {
override fun doWork(): Result {
Log.e("inDo", "work")
GlobalScope.launch {
val resource = authRepository.loginAsync("wmwdwnd@gmail.com", "sdnwnd").await()
when (resource) {
is Resource.Success -> {
Result.success()
Log.e("complete", "ass")
}
is Resource.Error -> {
Result.success()
Log.e("error", "asdd")
//when (resource.code) {}
}
else -> {
Result.success()
}
}
}
return Result.success()
}
}
//视图类
class WorkMnagerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_work_mnager)
val button = findViewById<Button>(R.id.button2)
button.setOnClickListener {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val data = Data.Builder()
.putString("tittle", "")
.build()
val oneTimeWorkRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java)
.setInputData(data)
.setConstraints(constraints)
.build()
WorkManager.getInstance().enqueue(oneTimeWorkRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
.observe(this, Observer {
it?.let {
if (it.state == WorkInfo.State.ENQUEUED) {
// Show the work state in text view
Log.e("ddd","Download enqueued.")
} else if (it.state == WorkInfo.State.BLOCKED) {
Log.e("ddd","Download blocked")
} else {
Log.e("ddd","Download running.")
}
}
})
}
}
}
答案 0 :(得分:1)
worker
类仅支持同步任务(WorkManager负责在后台执行器上启动doWork()
。来自Threading in Worker:
请注意,Worker.doWork()是一个同步调用-您应该以阻塞的方式完成整个后台工作,并在方法退出时完成它。
如果您需要异步运行某些内容,建议您使用CoroutineWorker
或ListenableWorker
。
您可以在Threading in WorkManager guide上找到更多信息。
答案 1 :(得分:0)
检查是否已连接到网络,因为已添加了约束
.setRequiredNetworkType(NetworkType.CONNECTED)
也可以尝试检查网络,您可以使用
进行检查val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnected == true
最后,您已将任务添加为异步任务,WorkManager
是同步工作的,请尝试对其进行更改。
答案 2 :(得分:0)
Workers
类在构造函数中必须只有两个参数
context: Context
和workerParameters: WorkerParameters
class UploadWorker (context: Context, workerParameters: WorkerParameters) {..}
在您的情况下,另一个val authRepository: AuthRepository
破坏了您的代码。
要将其他依赖项传递给Worker
,您可以使用WorkerFactory
,详细说明here