How to set timer in android?

后端 未结 21 904
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  你的背包
    2020-11-22 01:45

    Here is a simple reliable way...

    Put the following code in your Activity, and the tick() method will be called every second in the UI thread while your activity is in the "resumed" state. Of course, you can change the tick() method to do what you want, or to be called more or less frequently.

    @Override
    public void onPause() {
        _handler = null;
        super.onPause();
    }
    
    private Handler _handler;
    
    @Override
    public void onResume() {
        super.onResume();
        _handler = new Handler();
        Runnable r = new Runnable() {
            public void run() {
                if (_handler == _h0) {
                    tick();
                    _handler.postDelayed(this, 1000);
                }
            }
    
            private final Handler _h0 = _handler;
        };
        r.run();
    }
    
    private void tick() {
        System.out.println("Tick " + System.currentTimeMillis());
    }
    

    For those interested, the "_h0=_handler" code is necessary to avoid two timers running simultaneously if your activity is paused and resumed within the tick period.

提交回复
热议问题