android数字时钟每5秒更新一次

时间:2012-12-14 00:15:12

标签: android textview clock digital

这个想法是在前面屏幕顶部的一个方框中显示当前系统时间,数字格式如小时:分钟:秒。它需要不断更新。但是,如果每1秒更新秒数,则可能会使系统运行。因此,我希望用户能够选择更新速率(每1秒,5秒或10秒)。问题是:我如何每5秒更新一次textview? 我们写这段代码:

package com.example.software;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Time dtNow = new Time();
        dtNow.setToNow();
        int hours;
        int minutes;
        int second;
        int i=100;
        int j=0;
        TextView txt =(TextView) findViewById(R.id.txt_view);

        while(i>0){

            hours = dtNow.hour;
            minutes= dtNow.minute;
            second = dtNow.second;
            txt.setText(hours+":"+minutes+":"+second);
        try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {

                e.printStackTrace();
        }



        }

    }


}

我将此代码更新为:

package com.example.softwareproject;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

     Time dtNow = new Time();

     int hours;
     int minutes;
     int second;
     int i=100;
     int j=0;


     @Override
    public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         display();
    }

    public void display(){

        new Thread(new Runnable(){

            public void run() {

            while(i>0){
                    TextView txt =(TextView) findViewById(R.id.txt_view);
                    dtNow.setToNow();
                    hours = dtNow.hour;
                    minutes= dtNow.minute;
                    second = dtNow.second;
                    txt.setText(hours+":"+minutes+":"+second);


                        try{
                            Thread.sleep(5000);
                            }
                        catch (InterruptedException e) {
                            e.printStackTrace();
                            }
                        }
                 }
        }).start();

    }

}

但我仍然有这个错误:

[2012-12-14 03:54:25 - SoftwareProject] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.softwareproject/.MainActivity }
[2012-12-14 03:54:25 - SoftwareProject] ActivityManager: Warning: Activity not started, its current task has been brought to the front

并且应用程序停止了。

0 个答案:

没有答案