简体   繁体   中英

How destroy activity works?

I'm new in android development, and there is something about the life cycle activity that I don't understand, especially with the following example of application that i'm working on.

In my app, I have a Login activity and a Main activity.

  1. In my Login activity, with successful attempt, there is a Intent that start the main activity, and finish() the login activity.
    ==> There, my login activity is destroyed, so this should not show up again.

     Intent intent = new Intent(this, MainActivity.class); intent.putExtra("authentResult", tokenDto); startActivity(intent); finish(); //destroy activity to not open it with back button` 
  2. In my Main activity, I have a disconnect button that create an Intent that start a (new ?) login activity.
    ==> Until there, everything's normal, and the login activity is displyed.

     Intent loginActivity = new Intent(this, LoginActivity.class); 

    startActivity(loginActivity);

  3. In the login activity, using the Back button should close the app.
    To do that, I send an intent with special flag to the main activity to finish it (So the back button will not wake up the main activity), and then I finish the login activity. The onDestroy method is called and I see the login window close itself.
    ==> From here I expect the app to be closed. But a "new" login activity shows up, and i suspect that it would be the activity of the first point , so I'm a little lost there...

     public void onBackPressed() { Log.d(TAG, "BACK PRESSED - loginActivity"); //Finish MainActivity Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("EXIT", true); startActivity(intent); finish(); // finish login activity } 

In the onCreate in the mainActivity, I begin with this :

       if (getIntent().getBooleanExtra("EXIT", false)) {
             finish();
       }

Do anyone could explain to me what I'm missing, or show me a better way to close the app directly ?

Don't hesitate to telle me if something's not clear.

If you declare the Login activity as main activity in the Manifest, if you don't destroy it when you launch the second activity then i think the back button will do all you expect without any additional code, and if you press back key on the login activity it will go to phone home screen

On Android applications is the system that decides when to close/kill application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM