每秒重复一次脚本

时间:2013-12-22 18:29:57

标签: android

我为Android编写了一个倒计时应用程序,到目前为止,我已经设法从应用程序打开的那一刻开始显示时间,但它没有刷新。我认为它与使用postDelayed函数有关,但我不知道我是如何应用这个,我不能从文档中做任何事情。帮助将受到大力赞赏!

到目前为止我所拥有的:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Time now = new Time();
    now.setToNow();

    Time decision = new Time();
    decision.set(7, 0, 2014);

    long nowutc = now.toMillis(false);
    long decutc = decision.toMillis(false);

    long difference = decutc - nowutc;

    int days = (int) difference / 86400000;
    int hours = (int) (difference % 86400000)/3600000;
    int leftover = (days*86400000) + (hours*3600000);
    int minutes = (int) (difference - leftover)/60000;
    int secleft = (int) leftover + (minutes*60000);
    int seconds = (int) (difference-secleft)/1000;

    ((TextView)findViewById(R.id.time)).setText(days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ");
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

private int mInterval = 500; // ms
private Handler mHandler;
private TextView mTextView;

@Override
protected void onCreate(Bundle bundle) {
    setContentView(R.layout.whatever);
    mTexView = (TextView) findViewById(R.id.time);
    mHandler = new Handler();
    mHandler.post(mUpdateTime);
}

Runnable mUpdateTime = new Runnable() {
    @Override 
    public void run() {
        Time now = new Time();
        now.setToNow();

        Time decision = new Time();
        decision.set(7, 0, 2014);

        long nowutc = now.toMillis(false);
        long decutc = decision.toMillis(false);

        long difference = decutc - nowutc;

        int days = (int) difference / 86400000;
        int hours = (int) (difference % 86400000)/3600000;
        int leftover = (days*86400000) + (hours*3600000);
        int minutes = (int) (difference - leftover)/60000;
        int secleft = (int) leftover + (minutes*60000);
        int seconds = (int) (difference-secleft)/1000;
        mTextView.setText(days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ");
        mHandler.postDelayed(mUpdateTime, mInterval);
    }
};