我想爲android做一個鬧鐘應用程序我應該做的第一件事是不斷獲取系統的當前時間,所以我這樣做,但它只獲得當前第二個,沒有更多, ,有什麼幫助? 這裏是代碼:獲取當前時間不斷android
public class MainActivity extends Activity {
public Button time;
public TextView secondview;
public static int hours, mins, secs;
Handler main;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (Button) findViewById(R.id.button1);
secondview = (TextView) findViewById(R.id.textView2);
new Thread(new Runnable() {
@Override
public void run() {
secondview.setText(String.valueOf(secs));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
main = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Calendar mycal = Calendar.getInstance();
hours = mycal.get(Calendar.HOUR);
mins = mycal.get(Calendar.MINUTE);
secs = mycal.get(Calendar.SECOND);
secondview.setText(String.valueOf(secs));
}
};
}
}
使用報警管理器 –
使用這樣的線程是錯誤的,原因很多。它浪費CPU資源,速度慢,更新速度遠快於人類感知時間,並且無法工作(更改線程上的UI)。相反,你應該決定你想更新和使用計時器的頻率。每當定時器關閉時就獲取時間。 –
@GabeSechan非常感謝,非常感謝:「D –