0

I have a countdown timer app, but I need it to be able to run and count down even if the app is closed. I have been trying to learn SharedPreferences from youtube tutorials but I can't figure out how to get it to work. Are there easier options than SharedPreferences or could someone help me out with it? I've put my countdown timer code down below.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:ems="10"
        android:hint="Aeg"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.countdowntimerproov1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button button;
    EditText editText;
    long millisUntilFinished;
    int finalValue;



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

        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        editText = findViewById(R.id.editText);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String value = editText.getText().toString();
                int finalValue = Integer.parseInt(value);


                new CountDownTimer(finalValue, 1000) {
                    public void onTick(long millisUntilFinished) {
                        NumberFormat f = new DecimalFormat("00");
                        long hour = (millisUntilFinished / 3600000) % 24;
                        long min = (millisUntilFinished / 60000) % 60;
                        long sec = (millisUntilFinished / 1000) % 60;
                        textView.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
                    }
                    public void onFinish() {
                        textView.setText("00:00:00");
                    }
                }.start();


            }
        });

    }
}
Castino
  • 3
  • 2
  • SharedPreferences is used to save data. This data will be preserved, but it won't keep your code running when the activity is closed. Check out services (https://guides.codepath.com/android/starting-background-services) which aren't bound to an activity's lifecycle. – Josi Whitlock Jan 05 '22 at 17:29
  • As mentioned by @Josie, SharedPreferences used for save data only. When your app is finishing and countdown is running save the last countdown to shared preference and also the current time. When you start the app again, fetch last countdown time and current time, calculate elapsed countdown, and start the countdown again. – masoomyf Jan 12 '22 at 15:49

1 Answers1

0

Short Answer : Use Broadcast Receiver : How to run CountDownTimer in a Service in Android?

You are creating countdown timer in your Activity. Generally at a time only one Activity could run in foreground(*). Which means as soon as your phone receives a call or you press home-screen button your activity would go in paused state and timer would stop. Not only that, once you rotate you screen the timer would be reset because by rotation onCreate() is called again. If you close your app then all its activities would be destroyed - again no chance for timer to run. Hence its a bad idea to use Activity for a timer like app.

*(its possible to run more than one though : https://collaborate.pega.com/question/it-possible-run-2-activities-same-time)

  • Oh, okay, thanks. Sadly that first link is still very confusing, and I don't really understand how I can make a countdown timer with broadcast receiver – Castino Jan 05 '22 at 18:41
  • @Castino try this [demo countdown timer broadcast receiver](https://stackoverflow.com/a/69622122/16653700). – Alias Cartellano Jan 05 '22 at 21:40