How to close Android application in Kotlin
Asked Answered
U

6

19

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 ?

Underglaze answered 13/8, 2018 at 23:24 Comment(3)
Yes, startActivityForResult and setResult with some EXIT_CODE and go listening it back and propagating backwards(with more setResuts)Sparteine
@MarcosVasconcelos Because I searched and could not find example code could you post a small snip of code it is this line that has me confused val intent = Intent(this@MainActivity, PageTwoActivity::class.java) declaring the intent in is where we are lostUnderglaze
@MarcosVasconcelos I added and edit to my quest to show the structure of the code I use to construct and Intent in Kotlin NO RESULTSUnderglaze
E
40

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

Ela answered 14/8, 2018 at 19:41 Comment(0)
Q
4

This works:

android.os.Process.killProcess(android.os.Process.myPid())

...but with important caveats that have a heated discussion in this SO question, Why is calling Process.killProcess(Process.myPid()) a bad idea?

Quentinquercetin answered 29/3, 2021 at 2:5 Comment(1)
2023 SDK 31 Kotlin - this solution is the only one that works for me. The others outlined above leave my app in a state that you can tap on it from Recents, and it will freeze (I don't close from Main, but from some other activity below.)Hemicellulose
C
4

Since API 21 You can use

finishAndRemoveTask()
Corporeal answered 17/12, 2022 at 16:37 Comment(0)
B
2

for a particular button:

val btn3 = findViewById<Button>(R.id.button3)

set the task for that button:

btn3.setOnClickListener {
    finish()
    System.out.close()
}
Bronson answered 17/8, 2022 at 3:25 Comment(1)
The shortest answer, however simply calling finish() is enough :)Chukar
S
1

There's two solutions on this, working on yours code:

    val intent = Intent(context, MainActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
    intent.putBoolean(MainActivity.FINISH, true)
    finish()

Declare FINISH as val FINISH = "finish_key_extra"

And add this code at onCreate of MainActivity

    super.onCreate(state)
    boolean finish = getIntent().getBooleanExtra(FINISH, false) //default false if not set by argument
    if(finish) {
        finish();
        return;
    }

Since you using CLEAR_TOP and NEW_TASK you will have only that one activity on stack, so you finish it by sending a argument.

The other solution I mentioned is starting every Activity on your application with startActivityForResult(intent, REQUEST_CODE_X)

And at on every activity on application also have this code: (declare a int FINISH_APP to be used as result code somewhere)

void onActivityResult(int requestCode, int resultCode, Bundle result) {
     if(requestCode == AppIntents.REQUEST_CODE_X)
         if(resultCode == FINISH_APP){
             setResult(FINISH_APP);
             finish();
         }
}

And at any point you want to start closing the app you call:

             setResult(FINISH_APP);
             finish();

Note that the FINISH_APP is declared different from RESULT_OK, RESULT_CANCELED so it can still be used by your app.

Note: I'm a Java dev, not kotlin

Sparteine answered 14/8, 2018 at 13:53 Comment(4)
I appreciate your suggestions they look great tried both sorry to say we are both in the boat of "not Kotlin" dev too much red when I pasted the code in the simple project see comment to mducc for design of app if you can write in Java we can always convert Still looking for code to just close the app It should not be this difficult but if it wasn't then where would the fun beUnderglaze
It actually is, you just have to translate thisSparteine
@MarcosVasconcelow I did the translation and still lots of RED I did add the variables but no luck will let you know if I get a resultUnderglaze
The idea there is to remove the stack and finish the only one that lasts, you can simply create a new FinishActivity and call it with CLEAR_TOP | NEW_TASK and the only thing you do onCreate is to finish()Sparteine
E
0

Here's a technique that should remove it from the Recents screen (tested on numerous emulators past API 21):

First, we create a new Activity that specifically handles exiting the app:

package com.example.yourAppNameHere

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlin.system.exitProcess

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

        //Get The "Exit Screen" Layout
            setContentView(R.layout.activity_time_to_exit_app)

        //Immediately Exit App
            finishAndRemoveTask()

        //Exit Process
            exitProcess(-1)
    }
}

Second, when we want to exit the app, we simply switch to this activity, while simultaneously setting some flags to clear any pending tasks from the back stack (source):

startActivity(Intent(applicationContext, ActivityTimeToExitApp::class.java).also{it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK})

Please comment if there are any best practices concerns with this technique.

Exasperation answered 6/5, 2024 at 17:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.