Issues with Hilt on invoking a BroadcastReceiver

不羁的心 提交于 2021-02-05 10:43:18

问题


I'm facing a similar issue like this. I assume that Hilt is not able to invoke my BroadcastReceiver and I really don't have a clue how to make it work.

I tried with the solution provided. The code runs smoothly, but still the BroadcastReceiver won't get invoked.

This is what I did so far:

AndroidManifest.xml

<receiver android:name=".receiver.BatteryLevelReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BATTERY_LOW" />
                <action android:name="android.intent.action.BATTERY_OKAY" />
            </intent-filter>
</receiver>

<receiver android:name=".receiver.PowerConnectionReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
</receiver>

BatteryApp.kt

@HiltAndroidApp
class BatteryApp : Application()

HiltBroadcastReceiver.kt

abstract class HiltBroadcastReceiver : BroadcastReceiver() {
    @CallSuper
    override fun onReceive(context: Context, intent: Intent) {
    }
}

PowerConnectionReceiver.kt

@AndroidEntryPoint
class PowerConnectionReceiver : HiltBroadcastReceiver() {

    private lateinit var workManager: WorkManager
    private var status: String? = null

    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)

        when (intent.action) {
            Intent.ACTION_POWER_CONNECTED -> status = "POWER CONNECTED"
            Intent.ACTION_POWER_DISCONNECTED -> status = "POWER DISCONNECTED"
        }

        val data = Data.Builder()
            .putString("status", status)
            .build()

        workManager = WorkManager.getInstance(context)
        val notificationBuilder = OneTimeWorkRequest.Builder(NotifyWorker::class.java)
            .setInputData(data)
            .build()

        workManager.enqueue(notificationBuilder)
    }
}

The code from BatteryLevelReceiver.kt is similar to the one from PowerConnectionReceiver.kt, for the sake of keeping this post short, I won't post it here.

No matter which event was recognized by the system (BATTERY_LOW, ACTION_POWER_CONNECTED etc.), my app doesn't react on it.

Thank you very much in advance.

来源:https://stackoverflow.com/questions/65476494/issues-with-hilt-on-invoking-a-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!