Show elapsed time since pressing a button in Andro

2019-04-12 12:17发布

I want to be able to show the elapsed time in a textview or Chronometer held in a "Statistics" class since pressing a button located in another class. What would be the easiest way to implement this?.

Thanks

2条回答
\"骚年 ilove
2楼-- · 2019-04-12 12:58

Set up a tenth-second repeating timer and do the view update in a runnable handler.



    protected Timer timeTicker= new Timer("Ticker");
    private     Handler timerHandler    = new Handler();
    protected   int     timeTickDown        = 10;

    // onCreate() code

    timeTicker.scheduleAtFixedRate(tick, 0, 100); // 100 ms each

    // timer handlers


    protected TimerTask tick = new TimerTask() {
        public void run() {
            myTickTask();
        }
    };

    // Override this in Subclass to get or add specific tick behaviors
    protected void myTickTask() {
        if (timeTickDown == 0) { 
            timerHandler.post(doUpdateTimeout);
        }
        timeTickDown--;

    }

    private Runnable doUpdateTimeout = new Runnable() {
        public void run() {
            updateTimeout();
        }
    };

    private void updateTimeout() {
        timeTickDown = 10; // 10* 100ms == once a second
        // do something useful like sequencing a state machine
        // and gui babble.
    }
查看更多
ら.Afraid
3楼-- · 2019-04-12 13:06

What about setting a variable = System.currentTimeMillis() when you inflate the view? And at onDestroy substract that time from the current time ?

查看更多
登录 后发表回答