Android - Want app to perform tasks every second

后端 未结 4 535
-上瘾入骨i
-上瘾入骨i 2020-12-17 23:28

I\'m trying to get my countdown app to perform its function of updating my current time and date TextView and fire off its MyOnItemSelectedListener every second so that the

相关标签:
4条回答
  • 2020-12-17 23:41

    You can either use sendMessageAtTime() or postAtTime() to send yourself a message a second in the future, and handle it then.

    For more information.

    0 讨论(0)
  • 2020-12-17 23:44

    Try to use UpdateDisplay function like below:

    private void updateDisplay() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
    
            @Override
            public void run() {
                Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);
                mSecond = c.get(Calendar.SECOND);
    
                cDateDisplay.setText(new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("/")
                    .append(mMonth + 1).append("/")
                    .append(mYear).append(" "));
    
                cTimeDisplay.setText(
                    new StringBuilder()
                        .append(pad(mHour)).append(":")
                        .append(pad(mMinute)).append(":").append(pad(mSecond))
                );
            }
    
        },0,1000);//Update text every second
    }
    

    Finally, you must to call updateDisplay() in onCreate() function.
    I hope this code would help you finish what you want !

    0 讨论(0)
  • 2020-12-18 00:04

    To run it on the main thread:

            new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        yourMethodOnTheMainThread();
                    }
                });
            }
        },0,10000);
    
    0 讨论(0)
  • 2020-12-18 00:05

    Maybe you can also use Timer/TimerTask to fire a operation repeatedly: https://developer.android.com/reference/java/util/Timer.html

    0 讨论(0)
提交回复
热议问题