How to make a timer run in the background

不打扰是莪最后的温柔 提交于 2020-01-05 07:31:13

问题


How would i go about efficiently having a timer run in the background when the application is stopped? rite now i have not done anything and the timer will continue to run when the app has been stopped but some times it will stop running without me giving it the command. This is how i am currently running my timer:

    if(t == null){
   t = new Timer();
    t.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                public void run() {
                    if(DHPDPS==0){
                        money = (DPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    }else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
                        money = (DOTPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    } else{

                        money = (DPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    }
                    counter++;
                    //if(counter == 3000)
                    //   t.cancel();

                    // Display pay per second
                    if(counter <= DHPDPS || DHPDPS == 0){
                    t2.setText("Your pay per second is: $"+result);
                    }else{
                        t2.setText("Your pay per second is: $"+result2);
                    }
                }
            }); 
        }
    }, 20, 20);

It is declared in the onCreate(), thanks!


回答1:


For tasks running in the background you should be using an IntentService. It will keep running even if your activity is paused or removed by the OS.




回答2:


If your phones memory starts filling up it will close all the activities that are not actively being used.

For something like a timer it might be better to save the start time into SQLite and when the activity is reloaded reference it as a start point to calculate the duration.

Otherwise, if your intent that the timer keeps ticking turn it into an intent service.




回答3:



private fun startTimer() 
       var lastdata = PrefUtils.getpunchtime(this)
       var mEndTimediff = System.currentTimeMillis() - lastdata!!
       var mTimeLeftInMillis = viewModel.START_TIME_IN_MILLIS.toLong() - mEndTimediff

       viewModel.mCountDownTimer = object : CountDownTimer(mTimeLeftInMillis, 1000) {
           override fun onTick(millisUntilFinished: Long) {
               mTimeLeftInMillis = millisUntilFinished
               updateCountDownText(mTimeLeftInMillis)
           }

           override fun onFinish() {
               viewModel.mTimerRunning = false
           }
       }.start()

   }

   private fun updateCountDownText(mTimeLeftInMillis: Long) {

       val millis: Long = mTimeLeftInMillis
       val hms = String.format(
           "%02d : %02d: %02d", TimeUnit.MILLISECONDS.toHours(millis),
           TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(
               TimeUnit.MILLISECONDS.toHours(
                   millis
               )
           ),
           TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(
               TimeUnit.MILLISECONDS.toMinutes(
                   millis
               )
           )
       )

       binding.tvTimertime.setText(hms)
   }

SharePreference in store Last_time


       fun storepunchtime(context: Context, storepunchtime: Long) {
           val editor = getSharedPreferences(context).edit()
           editor.putLong(PUNCH_TIME, storepunchtime)
           editor.apply()
           editor.commit()
       }
       fun getpunchtime(context: Context): Long? {
           return getSharedPreferences(context).getLong(PUNCH_TIME, 0L)
       }


来源:https://stackoverflow.com/questions/11855415/how-to-make-a-timer-run-in-the-background

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!