Search code examples
javaandroidtimer

How to make a timer run in the background


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!


Solution

  • 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.