Should I always finish one activity before going to another?
Asked Answered
T

3

7

Do you always call finish() on some activity before going to another activity?

For example, in order to prevent user going to the previous activity via mobile back button, some people suggest that you should finish all activities, except the main one. This way, the back button always returns you to the main activity (or any other activity you think a user should be navigated). This is done by overriding back button behaviour.

Bad thing of this is when there is a dialog run from the Handler which try to runs after the activity finished (http://dimitar.me/android-displaying-dialogs-from-background-threads/).

What is your rule of thumb on this issue? Call finish() in some smarter way or overriding back button to direct user to page of your choice?

Tiger answered 2/11, 2011 at 8:25 Comment(0)
E
5

If you understood the workflow of an Android application, there should be no need to override the back-button (except for some special cases like Games for example).

If you don't want the user to get back to the previous Activity, finish it. There should be no need to override the back-button for that.

public class Activity1 extends Activity{

    // Some onclick-Handler
    public void onButtonClick(View v){
        Intent i = new Intent(this, Activity2.class);
        this.startActivity(i);
        // Don't want you to return:
        this.finish();
    }
}
Enamour answered 2/11, 2011 at 8:30 Comment(2)
But if a user preses the back button in an activity A and goes to the activity B, then the activity A remains active, right? Where do you suggest to finish the activity A in such cases? onPause or somewhere else?Tiger
In this case, you would finish it in the onStop()-method.Enamour
S
1

If you do not want the back button to go to the current activity on back press finish the activity.

If you have a dialog opened, overide the onPause method of the activity and close the dialog. onPause will be called when the activity goes offscreen.

We only overide the onBackPressed method when we need to do something specific otherwise in normal cases we just leave it.

Sonja answered 2/11, 2011 at 8:30 Comment(3)
I do not understand. Why overriding onPause when I can have a button in the dialog and call dialog.dismiss()?Tiger
there are situations when the user can leave the activity like pressing home button or a notification. In these cases you can hide the dialog in the onPause method.Sonja
Are you talking about dialog as part of the activity as it is hidden as well when you press the Home button.Tiger
I
0

If you want to open another activity and want to finish the previous activity then use the finish(); function after calling the intent of another activity.

it will finish the current activity and open the new activity.

Ingenuous answered 2/11, 2011 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.