这个想法是在前屏幕顶部的一个框中显示当前系统时间,以小时:分钟:秒等数字格式显示。它需要不断更新。但是,如果您每 1 秒更新一次秒数,它可能会使系统停机。因此,我希望用户能够选择更新速率(每 1 秒、5 秒或 10 秒)。问题是:我如何每 5 秒更新一次文本视图?我们编写这段代码:
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
并且应用程序停止了。