Search code examples
androidkotlinandroid-activitybroadcastreceiver

Start New Activity with Sending Broadcast in Kotlin


I want to Start DashBoardActivity after a successful attempt on LoginActivity. I also want to Broadcast UserToken after logged in. But either I can startActivity() or sendBroadcast(). If I used the following code in LoginActivity.kt then

btnLogin.setOnClickListener {
    if(loginSuccess){
         sendBroadcast(Intent("TEST"))
         startActivity(Intent(this, DashboardActivity::class.java))
         finish()
    }
}

Dashboard Activity will open, but Broadcast onReceive() does not work. Please help me to properly do this task.

DashBoardActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        registerReceiver(userDataChangeReceiver,
            IntentFilter("TEST"))
    }

    private val userDataChangeReceiver = object: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            println("succeess!")
        }
    }
}

Solution

  • override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)
    
      val userDataChangeReceiver = object: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            println("succeess!")
        }
     }
    
        registerReceiver(userDataChangeReceiver,
            IntentFilter("TEST"))
     }
    }