Hill Injection无法与BroadcastReceiver一起使用

问题描述 投票:4回答:1

使用Hilt在BroadcastReceiver内部进行依赖注入不起作用。我尝试使用来自BroadcastReceiver的警报来调用MainActivity,并且我正在获取UninitializedPropertyAccessException。根据文档,它应该与向接收器添加@AndroidEntryPoint注释一样简单,但不是。

示例代码:]

App.kt:

@HiltAndroidApp
class App: Application() {
    override fun onCreate() {
        super.onCreate()
        Log.d(App::class.simpleName, "onCreate: Application")
    }
}

TestHiltInjection.kt:

class TestHiltInjection @Inject constructor() {

    operator fun invoke() {
        Log.d(TestHiltInjection::class.java.simpleName, "invoke called.")
    }
}

HiltBroadcastReceiver.kt:

@AndroidEntryPoint
class HiltBroadcastReceiver : BroadcastReceiver() {

    @Inject lateinit var testHiltInjection: TestHiltInjection

    override fun onReceive(context: Context?, intent: Intent?) {
        testHiltInjection()
    }
}

MainActivity.kt:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        val pending = PendingIntent
            .getBroadcast(this, 0, Intent(this, HiltBroadcastReceiver::class.java), 0)
        manager.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            15000, 15000,
            pending
        )
    }
}

输出Logcat:

kotlin.UninitializedPropertyAccessException: lateinit property testHiltInjection has not been initialized
android android-jetpack dagger-hilt hilt-dagger android-hilt
1个回答
2
投票

我认为目前尚不支持BroadcastReceiver。在https://dagger.dev/hilt/android-entry-point中说

注意:Hilt当前仅支持扩展ComponentActivity的活动和扩展androidx库Fragment的片段,而不支持Android平台中的(现已不推荐使用的)Fragment。

[内部运作方式:Hilt为@AndroidEntryPoint带注释的组件(活动,片段,BroadcastReceiver等)创建抽象类,并且您的BroadcastReceiver在字节码转换中将生成的类扩展为基类。在基类onReceive中,将注入对象。但是在生成的字节码类中,未调用超类onReceive方法。这就是为什么不注入对象的原因。要测试,请在testHiltInjection()类的HiltBroadcastReceiver之前添加以下代码。顺便说一下,它仍然处于Alpha模式。

((HiltBroadcastReceiver_GeneratedInjector) BroadcastReceiverComponentManager.generatedComponent(context)).injectHiltBroadcastReceiver(UnsafeCasts.<HiltBroadcastReceiver>unsafeCast(this));
© www.soinside.com 2019 - 2024. All rights reserved.