Search code examples
androidkotlinexit

How do I exit a Kotlin app from Non-Main Activity


I have an app with the following structure:

I have a launcher Activity -> MainActivity.kt, which in its onCreate, calls the SplashScreen.kt.

In this SplashScreen.kt, I download data from my server and then finally open Dashboard.kt

In the Dashboard.kt, whenever, I press back twice, I want to quit the application.

This is how I've set up the quit function

private fun quit(){
        if (lastBackPressed + 2000 > System.currentTimeMillis()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.finishAffinity()
            } else{
                this.finish()
                exitProcess(0)
            }
        }
        else Toast.makeText(
            context,
            "Press once again to exit!",
            Toast.LENGTH_SHORT
        ).show()
        lastBackPressed = System.currentTimeMillis()
    }

To do so, I've referenced the following questions:

However, all the solutions there, could only help me to quit my Dashboard.kt

As soon as Dashboard.kt is quit, MainActivity starts again and loads the SplashScreen.kt, which in turn loads the Dashboard.kt (again).

Is there a better and efficient way to quit the app, directly from the Dashboard.kt activity?


Solution

  • In the app's manifest file, add android:noHistory="true" flag in the main activity. this will allow your app to open MainActivity and then remove it from the stack whenever another activity is called.

    For example in your case:

    MainActivity.kt

    -> SplashScreen.kt

    -> Dashboard.kt (MainActivity.kt remains in the stack.)

    If you add android:noHistory="true" flag in the main activity then what happens its as below:

    MainActivity.kt

    -> SplashScreen.kt (MainActivity.kt will be removed from the stack.)

    -> Dashboard.kt

    -> Press back twice here and you'll be able to exit the app.