Search code examples
androidactivity-lifecycle

Android: click event after Activity.onPause()


There are two buttons, button A starts another activity inside its onClickListener using simple Activity.startActivity() method, button B does some other work inside its onClickListener.

When I click button B and immediately after button A, then new activity is started, onPause() lifecycle event for old activity is fired, but also onClick event for second button is fired, but after Activity.onPause() which leads to some state inconsistencies in my app.

Is there any way to prevent touch/click events from being delivered after onPause() without using isPaused flag?

**Edit:**My code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonA = (Button) findViewById(R.id.activity_button);
        buttonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, TestActivity.class));
            }
        });

        Button buttonB = (Button) findViewById(R.id.log_button);
        buttonB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("TEST", "onClick");
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("TEST", "onPause");
    }
}

Basically if you are fast enough and click button B right after button A then B's onClick is fired after onPause.


Solution

  • This whole concept can be easily solved using ViewModels + lifecycle-aware LiveDatas where LiveData expose events to UI-layer only when it's allowed.