Kotlin: Unresolved local class when using BroadcastReceiver in Activity

柔情痞子 提交于 2019-12-03 10:01:53

The fix is to specify the exact type of your variable, type inference isn't working in this case for some reason (probably a Kotlin bug).

So instead of this:

private val broadcastReceiver = object : BroadcastReceiver()

Use this:

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver()

Looks like some bug and I think it should be on Kotlin issue tracker, but I guess that you can fix it for now by defining receiver as a class:

abstract class BaseActivity : Activity {

    companion object {
        private const val LOG_TAG = "BaseActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,
                IntentFilter(MY_FILTER))
    }

    override fun onStop() {
        super.onStop()
        if(isFinishing){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
        }
    }

    private val broadcastReceiver = MyBroadcastReceiver()

    inner class MyBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) = when (intent?.action) {
            MY_FILTER -> Log.d(LOG_TAG, "This is my filter!")
            else -> Log.e(LOG_TAG, "Hello action ${intent?.action}")
        }
    }
}

For completeness: Declaring the variable as protected works as well.

protected val broadcastReceiver = object : BroadcastReceiver()

I imagine anything besides private works.

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