本文介绍了使用Hilt注入CoroutineWorker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用匕首刀柄注入协程工人,我已经按照文档中的所有说明进行操作

I am trying to inject a coroutine worker using dagger hilt, I 've followed all the instructions in the documentation

https://developer.android.com/training/dependency-injection/hilt-jetpack 旨在供工人"使用不是协程工人"..

https://developer.android.com/training/dependency-injection/hilt-jetpackwhich was intended for "Worker" not "coroutine Worker"..

但是它给出了一个错误:

but it gives an error :

java.lang.NoSuchMethodError:没有接口方法getBackgroundExecutor()Ljava/util/concurrent/Executor

..在stackoverflow上发布了相同的问题,答案不适合我的情况

..the same question was posted on stackoverflow with an answer that doesn't suit my case

无法使用Hilt注入workmanager构造函数

这是代码和错误

如果能提供帮助,我将不胜感激...这是我的代码

I would be grateful if anyone can help...here's my code

package com.example.moviemania.work

import android.content.Context
import androidx.hilt.Assisted
import androidx.hilt.work.WorkerInject
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.example.moviemania.repository.MainRepository
import retrofit2.HttpException

class RefreshDataWorker @WorkerInject constructor (
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    val mainRepository: MainRepository
    ) : CoroutineWorker(appContext,params) {

    companion object {
        const val WORK_NAME = "com.example.moviemania.work.RefreshDataWorker"
    }

    override suspend fun doWork(): Result {
        try {
            mainRepository.refreshMovies()
        }catch (e: HttpException){
            return Result.retry()
        }
        return Result.success()
    }
}

@HiltAndroidApp
class MoviesApp : Application(), Configuration.Provider {
    @Inject lateinit var workerFactory: HiltWorkerFactory

    private val applicationScope = CoroutineScope(Dispatchers.Default)
    override fun getWorkManagerConfiguration() =
        Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.DEBUG)
            .build()


    override fun onCreate() {
        super.onCreate()
        delayedInit()
    }

    private fun delayedInit() {
        applicationScope.launch {
            setupRecurringWork()
        }
    }
    private fun setupRecurringWork(){
        val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(1,TimeUnit.DAYS).build()
        WorkManager.getInstance(applicationContext).enqueueUniquePeriodicWork(
            RefreshDataWorker.WORK_NAME,
            ExistingPeriodicWorkPolicy.KEEP,
            repeatingRequest
        )
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.moviemania">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:name=".MoviesApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MovieMania">
        <activity android:name=".ui.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="com.example.moviemania.workmanager-init"
            tools:node="remove" />
    </application>

</manifest>

这是错误

2021-01-11 09:23:44.685 29929-29960/com.example.moviemania E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
    Process: com.example.moviemania, PID: 29929
    java.lang.NoSuchMethodError: No interface method getBackgroundExecutor()Ljava/util/concurrent/Executor; in class Landroidx/work/impl/utils/taskexecutor/TaskExecutor; or its super classes (declaration of 'androidx.work.impl.utils.taskexecutor.TaskExecutor' appears in /data/app/com.example.moviemania-6m_-4lzXG2Ud-HIb1asUiQ==/base.apk)
        at androidx.work.CoroutineWorker.<init>(CoroutineWorker.kt:52)
        at com.example.moviemania.work.RefreshDataWorker.<init>(RefreshDataWorker.kt:22)
        at com.example.moviemania.work.RefreshDataWorker_AssistedFactory.create(RefreshDataWorker_AssistedFactory.java:25)
        at com.example.moviemania.work.RefreshDataWorker_AssistedFactory.create(RefreshDataWorker_AssistedFactory.java:13)
        at androidx.hilt.work.HiltWorkerFactory.createWorker(HiltWorkerFactory.java:55)
        at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:83)
        at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:242)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)

推荐答案

我认为这是不正确的导入语句:以下是代码段

I think it's an incorrect import statement: Here are the snippets

请检查您的Hilt模块是否导入错误.

Please check your Hilt Modules for bad imports.

PS:我已经为您提供了进口

    <application
    ...
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="${applicationId}.workmanager-init"
            tools:node="remove" />
    </application>

MyApplication.kt

import android.app.Application
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import javax.inject.Inject

@HiltAndroidApp
class MyApplication : Application(), Configuration.Provider {
    @Inject
    lateinit var workerFactory: HiltWorkerFactory

    private val applicationScope = CoroutineScope(Dispatchers.Default)

    override fun getWorkManagerConfiguration() =
        Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.DEBUG)
            .build()


    override fun onCreate() {
        super.onCreate()
        delayedInit()
    }

    private fun delayedInit() {
        applicationScope.launch {
            setupRecurringWork()
        }
    }

    private fun setupRecurringWork(){
        val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(1, TimeUnit.DAYS).build()

        WorkManager.getInstance(applicationContext).enqueueUniquePeriodicWork(
            RefreshDataWorker.WORK_NAME,
            ExistingPeriodicWorkPolicy.KEEP,
            repeatingRequest
        )
    }
}

RefreshDataWorker.kt

import android.content.Context
import androidx.hilt.Assisted
import androidx.hilt.work.WorkerInject
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import java.lang.Exception

class RefreshDataWorker @WorkerInject constructor (
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val mainRepository: MainRepository
    ) : CoroutineWorker(appContext,params) {

    companion object {
        const val WORK_NAME = "com.example.moviemania.work.RefreshDataWorker"
    }

    override suspend fun doWork(): Result {
        try {
            mainRepository.refreshMovies()
        }catch (e: Exception){
            return Result.retry()
        }
        return Result.success()
    }
}

MainRepository.kt

import android.util.Log
import javax.inject.Inject

class MainRepository @Inject constructor() {
    fun refreshMovies() {
        Log.d("ManoO", "Hello first time from worker: initiated immediately")
    }
}

成绩脚本

项目

buildscript {
    ...

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.21"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.30.1-alpha'
    }
}

应用

dependencies {
    ....

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2"

    implementation "com.google.dagger:hilt-android:2.30.1-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.30.1-alpha"
    implementation 'androidx.hilt:hilt-work:1.0.0-alpha02'
    kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

    def work_version = "2.5.0-beta02"
    implementation "androidx.work:work-runtime-ktx:$work_version"

}

这篇关于使用Hilt注入CoroutineWorker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:25