Skip to content
Advertisement

I want to change activity and reset timer after it finishes. Android Studio

So basically I made one minute countdown in Android Studio using java. As soon as timer riches “0“, I want to change activities and reset timer. so that when I visit this activity again, timer would work. Here’s my java code:

public class BeginAfter extends AppCompatActivity {

    TextView textView;

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

        textView = findViewById(R.id.timer);

        long duration = TimeUnit.MINUTES.toMillis(1);

        new CountDownTimer(duration, 1000){
            @Override
            public void onTick(long l) {
                String sDuration =
                        String.format(
                                Locale.ENGLISH,
                                "%02d",
                                TimeUnit.MILLISECONDS.toSeconds(l) -
                                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l))
                        );

                textView.setText(sDuration);
            }

            @Override
            public void onFinish() {
                //Reset and change activity
            }
        }.start();
    }
}

And here’s my xml code:

<TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#d10e00"
        android:textSize="37dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.064" />

Advertisement

Answer

You do the task by adding the following code to your activity:

CountdownTimer.onFinish(){
CountdownTimer.cancel()
startActivity(new Intent(CurrentActivity.this, NextActivity.class));
}

Please tell if it worked for you or not

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement