Search code examples
androidandroid-intentkotlin

How to close Android application in Kotlin


In JAVA we can close the application. We trying to develop skills with Kotlin and feel we are using the correct syntax to close the application. The issue is that the code only works if you close the app before going to the Second Page and back to the MainActivity which is the launcher activity code below

    fun onTV(view: View){
    exitProcess()
}

private fun exitProcess() {
    //finish()
    System.exit(-1)
}

Both finish and System.exit(-1) work if selected first without navigating to PageTwoActivity

The onTV is the onClick property of a TextView My guess is that we need to clear the Stack buy setting Flags so the question is what is the syntax for this in Kotlin? Remember we are on the launcher page MainActivity. Do we need an Intent for results?

Ok I tried this code with no improvement

    val intent = Intent(context, MainActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOIntent.FLAG_ACTIVITY_NEW_TASK
    finish()

We are close here is the code as it stands now the issue is still that while this will close the app if you do NOT navigate to the PageTwo and click the button to close the app right after it starts

    fun onTV(view: View){
    onBYE()
}

 fun onBYE() {
     exitProcess(-1)
 }

So I guess the question is how to clear PageTwo from the stack when onBYE is executed ?


Solution

  • Grendel here is the absolute easiest two ways to close the Kotlin App the first way will open the app on PageTwo when it is reloaded not elegant but I included on the chance that someone has a Splash Screen

         moveTaskToBack(true);
         exitProcess(-1)
    

    The second way is so simple and old you are going to scream It will close the Kotlin App and when reloaded the MainActivity is shown first

    finishAffinity()
    

    I tested this with Nexus 9 API 26 I do not have a Samsung Galaxy S2 but feel free to mail me one ha ha