如何在片段中关闭应用程序(后台)时保持计时器 运行

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

这段代码 运行 如果我把它写在 activity 中是完美的,但是它在 fragment.And 中发送 运行 我想要它 运行 它在应用程序被杀死后出现在后台。

这是我的倒计时

 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();


    }

这是我将时间转换为分秒的地方

  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);
    }

这是我的 OnStart() 方法

 @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();
        }
    }
}

这是我的 onStop() 方法

 @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();
    }
}

在此处更新按钮

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

对于 运行 应用终止后的任务,考虑在 android

中使用 background services