问题
In my android application, I have a button that, when clicked opens another activity. The problem is that the user could keep tapping on that button many times quickly and it would open a lot of those new activities. How can I force it so that only one of those activities can be open at a time?
I want to avoid doing big things like disabling buttons or putting loading screens.
回答1:
If the scenario is as simple as you describe, you can launch the Activity with FLAG_ACTIVITY_SINGLE_TOP. That will prevent new instances from being created if one has already been shown. A crude example:
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this, CalledActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}, 1000);
}
});
Rapid-pressing on the button will create many instances of CalledActivity
without the Intent flag.
回答2:
Set Intent.FLAG_ACTIVITY_SINGLE_TOP
. This ensures only one instance of the Activity will be created:
If set, the activity will not be launched if it is already running at the top of the history stack.
http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_SINGLE_TOP
来源:https://stackoverflow.com/questions/27613026/how-to-flag-only-one-instance-of-an-activity-in-android