jason
jason

Reputation: 7164

How to prevent an activity from being initialized multiple times

I have an Android app, when a user taps a button multiple times quickly, same activity is initialized multiple times.

To prevent this, I added android:launchMode="singleInstance" in Manifest file. But now, when an activity calls itself, it doesn't work.

I also tried

Intent myintent = getIntent();
myintent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 

But this didn't work either.

How can I prevent having multiple activities when user clicks a button multiple times quickly, and how can I have same activity call itself correctly. Thanks.

Upvotes: 2

Views: 120

Answers (2)

J Whitfield
J Whitfield

Reputation: 755

You could try disabling the button after the first click has been detected.

Button button = theView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.isEnabled()){
                    v.setEnabled(false);
                }
                //Call your new activity here
                ...activity stuff...
            }
        });

Upvotes: 1

Engraver
Engraver

Reputation: 86

Yeah, this happens if you are "trigger happy". You can also in many situations use multi-touch to activate a bunch of options at the same time. If you really need to solve this, you can look at disabling elements like J Whitfield suggested (element.setEnabled(false) or element.setClickable(false)) or intercepting onTouch.

Upvotes: 1

Related Questions