androidtextviewmessagetoastchronometer

Two toast or normal messages ( one after another ) in chronometer app


I'm not very good with Java and Android, but I want to build a simple chronometer app. I've created the buttons Start, Stop/Pause, Reset and it works, but I want to display message/text ("good") at a fixed time (for example at 00:15 seconds), then the message must hide and a new message must show at 00:28 seconds ("super") and also hide. I'm pasting the part of the code from MainActivity.java.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);
    chronometer = findViewById(id.chronometer);
    chronometer.setFormat("(%m,%s)");
    chronometer.setBase(SystemClock.elapsedRealtime());
    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 15000) {

                Toast.makeText(MainActivity.this, "Good!", Toast.LENGTH_SHORT).show();
            }
            if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 28000) {

                Toast.makeText(MainActivity.this, "Super!", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

This code currently generates the first message at 00:15 seconds, but the message stays until 00:35-6 seconds and then the second message is shown, but both messages start to show randomly.

I've tried to change if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 15000) to if ((SystemClock.elapsedRealtime() - chronometer.getBase()) == 15000), but this it does not work at all.

I've searched everywhere and did some tests for days now, but no result on how to do it. I've tested also with text view, but no good. If someone could help me on how to resolve this issue with toast messages or text view or some other way. Thank you very much in advance.


Solution

  • This is because you're showing the toast messages multiple times. For every time after 1500 milliseconds has passed, (SystemClock.elapsedRealtime() - chronometer.getBase()) >= 15000 is always true.

    If you're just looking to show the toast at 15 seconds, then you can find out which second the chronometer has ticked for and check whether it is equal to 15. There are plenty of ways to do this, but something like:

    ((SystemClock.elapsedRealtime() - it.getBase()) / 1000) * 1000 == 15000L