androidandroid-fragmentstimersharedpreferencescountdowntimer

HOW TO KEEP TIMER RUNNING WHEN CLOSING THE APP (Background) IN A FRAGMENT


This piece of code runs perfectly if I write it in an Activity but it doesn't run in a Fragment. And I want it to run in the background after the app is killed.

This is my countdowntimer

public void bonus(){
    mEndTime = System.currentTimeMillis() + timeleftinmillis;
    Log.i("timeadd", String.valueOf(mEndTime));
    countDownTimer = new CountDownTimer(timeleftinmillis,1000) {
        @Override
        public void onTick(long l) {
            timeleftinmillis=l;
            updateTimer();
        }

        @Override
        public void onFinish() {
            mrunning=false;
            updateButtons();
        }
    }.start();
    mrunning=true;
    bonusmoney.setText( String.valueOf(clickcount));
    updateButtons();
}

Here is where I am converting time into minutes and seconds

public void updateTimer (){
    long min = (timeleftinmillis/1000) / 60;
    long sec = (timeleftinmillis/1000) % 60;

    String timeformat = String.format(Locale.getDefault(),"%02d:%02d",min,sec);
    timerbonusview.setText(timeformat);
}

This is my OnStart() method

@Override
public void onStart() {
    super.onStart();
    SharedPreferences prefs = getContext().getSharedPreferences("prefs", MODE_PRIVATE);
    timeleftinmillis = prefs.getLong("millisLeft", timeinmillis);
    mrunning = prefs.getBoolean("timerRunning", false);
    updateTimer();
    updateButtons();

    if (mrunning) {
        mEndTime = prefs.getLong("endTime", 0);
        Log.i("endtime", String.valueOf(mEndTime));
        timeleftinmillis = mEndTime - System.currentTimeMillis();
        Log.i("timeleft", String.valueOf(timeleftinmillis));
        if (timeleftinmillis < 0) {
            timeleftinmillis = 0;
            mrunning = false;
            Log.i("timebonus", "less than zero");
            updateTimer();
            updateButtons();
        } else {
                bonus();
        }
    }
}

This is my onStop() method

@Override
public void onStop() {
    super.onStop();
    SharedPreferences prefs = getContext().getSharedPreferences("prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("millisLeft", timeleftinmillis);
    editor.putBoolean("timerRunning", mrunning);
    editor.putLong("endTime", mEndTime);
    editor.apply();
    if (countDownTimer != null) {
        countDownTimer.cancel();
    }
}

updating buttons here

private void updateButtons() {
    if (mrunning) {
        dailyearningsbtn.setVisibility(View.INVISIBLE);
    }else {
        dailyearningsbtn.setVisibility(View.VISIBLE);
    }
}

Solution

  • For running tasks after app is killed consider using background services in android