user1928775
user1928775

Reputation: 355

Keep Timer Ticking in Background

How can I keep the value of my timer resuming after going to another activity , my problem is that it's set to default if I switched to another activity I thought of using sharedpreference but it won't help because I need it to keep decrementing in the background.

    public void reset()
    {
        countDownTimer.cancel();
    }

    private void setTimer() {
        int time = 5;
        if(countDownTimer==null)
        {               
            totalTimeCountInMilliseconds = 60 * time * 1000;
        }
        else
        {
            reset();
            totalTimeCountInMilliseconds = 60 * time * 1000;                
        }
    }

    private void startTimer() {         

        countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
            // 500 means, onTick function will be called at every 500
            // milliseconds

            //@Override
            public void onTick(long leftTimeInMilliseconds) {
                seconds = leftTimeInMilliseconds / 1000;

                textViewShowTime.setText(String.format("%02d", seconds / 60)
                        + ":" + String.format("%02d", seconds % 60));
                // format the textview to show the easily readable format
            } 

            @Override
            public void onFinish() {
                // this function will be called when the timecount is finished
                textViewShowTime.setText("Time up!");
                textViewShowTime.setVisibility(View.VISIBLE);

            }

        }.start();

    }

Upvotes: 1

Views: 295

Answers (1)

marcinj
marcinj

Reputation: 49986

You should stop your CountDownTimer in onPause and restart in onResume, your textViewShowTime might not be valid while your activity is in background.

If you need to call some code every 500ms no matter what activity you are in, then consider using AlarmManager.

Upvotes: 1

Related Questions