How to prevent the activity from loading twice on pressing the button

Add this to your Activity definition in AndroidManifest.xml...

android:launchMode = "singleTop"

For example:

<activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:launchMode = "singleTop"/>

In the button's event listener, disable the button and show another activity.

    Button b = (Button) view;
    b.setEnabled(false);

    Intent i = new Intent(this, AnotherActitivty.class);
    startActivity(i);

Override onResume() to re-enable the button.

@Override
    protected void onResume() {
        super.onResume();

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setEnabled(true);
    }

You can use the intent flags like this.

Intent intent = new Intent(Class.class);    
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
activity.startActivity(intent);

It will make only one activity be open at the top of the history stack.


Since SO doesn't allow me to comment on other answers, I have to pollute this thread with a new answer.

Common answers for the "activity opens twice" problem and my experiences with these solutions (Android 7.1.1):

  1. Disable button that starts the activity: Works but feels a little clumsy. If you have multiple ways to start the activity in your app (e.g. a button in the action bar AND by clicking on an item in a list view), you have to keep track of the enabled/disabled state of multiple GUI elements. Plus it's not very convenient to disable clicked items in a list view, for example. So, not a very universal approach.
  2. launchMode="singleInstance": Not working with startActivityForResult(), breaks back navigation with startActivity(), not recommended for regular applications by Android manifest documentation.
  3. launchMode="singleTask": Not working with startActivityForResult(), not recommended for regular applications by Android manifest documentation.
  4. FLAG_ACTIVITY_REORDER_TO_FRONT: Breaks back button.
  5. FLAG_ACTIVITY_SINGLE_TOP: Not working, activity is still opened twice.
  6. FLAG_ACTIVITY_CLEAR_TOP: This is the only one working for me.

EDIT: This was for starting activities with startActivity(). When using startActivityForResult() I need to set both FLAG_ACTIVITY_SINGLE_TOP and FLAG_ACTIVITY_CLEAR_TOP.


It was only working for me when startActivity(intent)

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);