How to flag only one instance of an activity in android?

我的未来我决定 提交于 2019-12-13 07:46:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!