Why are SingleTop activities sometimes created multiple timesAsk Question

问题:

I have an activity with a launch mode set to singleTop in the manifest. However if this activity is started multiple times through startActivity called one after another, multiple instances are still created.

Here is the code that demonstrates the behavior. MainActivity displays a single button that start SingleTopActivity twice when clicked. SingleTopActivity displays a message received from MainActivity.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button startActivity = (Button) findViewById(R.id.startActivity);
        startActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSingleTopActivity("first");
                startSingleTopActivity("second");
            }
        });
    }

    private void startSingleTopActivity(@NonNull String message) {
        Intent intent = new Intent(this, SingleTopActivity.class);
        intent.putExtra(SingleTopActivity.EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

public class SingleTopActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "MESSAGE";

    private TextView mMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_single_top);

        getSupportActionBar().setTitle("SingleTopActivity");

        mMessage = (TextView) findViewById(R.id.message);
        mMessage.setText(getIntent().getStringExtra(EXTRA_MESSAGE));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String message = intent.getStringExtra(EXTRA_MESSAGE);
        mMessage.setText(mMessage.getText() + " " + message);
    }
}

When no additional intent flags are present SingleTopActivity with second message is launched. When navigated back SingleTopActivity with first message appears instead of MainActivity.

However if launched in debugger (so starting activity takes longer time due to breakpoints etc.), or when flags like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_CLEAR_TOP are set only one instance of SingleTopActivity is launched, as expected.

Why does singleTop not work as expected in this case?

回答1:


As this page says, if a activity is set to singletop, only if the activity is in top of the task, it won't be created again. In your code,when you call startSingleTopActivity("second");,the top activity of the task is MainActivity not SingleTopActivity, so it will be created twice.

标签:
© 2014 TuiCode, Inc.