Question

In my android game, there is an arcade mode, which runs for 60 seconds. UI has to be updated every second. Is it advisable to use CountDownTimer to implement this because as far af i know this class does not run on separate thread ? What are other ways or best way to do this without affecting user experience ?

EXACT CODE WHICH SOLVED MY PROBLEM

new Thread(new Runnable() {

             // this creates timer in another thread

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        long starttime = System.currentTimeMillis();
                        time=60;
                        while(time>0)
                        {
                            SystemClock.sleep(1000);
                            long currenttime = System.currentTimeMillis();
                            time= (int) (60-((currenttime-starttime)/1000));
            // this updates the UI
                            timerhandler.post(new Runnable()
                            {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    tv0.setText(time + " s");
                                }

                            });
                        }
                    }

                }).start();
Was it helpful?

Solution

Use

new Handler().postDelayed(new Runnable(){
    @Override
    public void run(){
        // Your code
    }
}, 60*1000));

OTHER TIPS

You can make use of Timer and TimerTask Class. Example (It gives the delay of 6 seconds. Its better to use seperate thread for this)

   Timer timer = new Timer("My Timer");
   TimerTask task = new TimerTask() {

        @Override
        public void run() {
            System.out.println("Timer task completed .......");

        }
    };
    System.out.println("Timer task started.......");
    timer.schedule(task, 0, 6000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top