Search code examples
androidsamsung-mobile

Finish() not working for Activity in Some Devices


Here is my code

private fun startMainActivity() {
    startActivity(Intent(this, MainActivityTab::class.java))
    finish()
}

Working fine in all devices but my Samsung device. When I press the back button in the MainActivityTab activity, it takes me back to the previous activity.

How to make this work for all the devices?

Device: Samsung A30s


Solution

  • You can use Intent flag like FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK to achieve this. Check below:

    val intent = Intent(this, MainActivityTab::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
    startActivity(intent)
    

    It will totally clears all previous activity(s) and start new activity

    For transition use any one from below based on your requirement:

    overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
    

    Or

    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)