未调用Workmanager Worker类的doWork()方法

时间:2019-08-19 11:27:05

标签: android kotlin android-workmanager

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.")
                        }
                    }
                })
        }
    }
}

3 个答案:

答案 0 :(得分:1)

worker类仅支持同步任务(WorkManager负责在后台执行器上启动doWork()。来自Threading in Worker

  

请注意,Worker.doWork()是一个同步调用-您应该以阻塞的方式完成整个后台工作,并在方法退出时完成它。

如果您需要异步运行某些内容,建议您使用CoroutineWorkerListenableWorker

您可以在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: ContextworkerParameters: WorkerParameters

class UploadWorker (context: Context, workerParameters: WorkerParameters) {..}

在您的情况下,另一个val authRepository: AuthRepository破坏了您的代码。 要将其他依赖项传递给Worker,您可以使用WorkerFactory,详细说明here