How to close Android application in Kotlin

前端 未结 2 857
执念已碎
执念已碎 2021-01-13 10:56

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 o

相关标签:
2条回答
  • 2021-01-13 11:20

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

    val intent = Intent(context, MainActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOIntent.FLAG_ACTIVITY_NEW_TASK
    intent.putBooleanExtra(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

    0 讨论(0)
  • 2021-01-13 11:39

    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

    0 讨论(0)
提交回复
热议问题