HanderとTimerを使用して時計を表示!
Activity内で現在の時刻を表示するTextViewを作成してみます。
使用するのは、Handler、Timer、TimerTaskクラスです。
public class MainActivity extends Activity {
private Handler mHandler;
private Timer mTimer;
// 時刻表示のフォーマット
private static SimpleDateFormat mSimpleDataFormat = new SimpleDateFormat("yyyy年 MM月dd日 HH:mm:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mHandler = new Handler(getMainLooper());
mTimer = new Timer();
// 一秒ごとに定期的に実行します。
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
String nowDate = mSimpleDataFormat.format(calendar.getTime());
// 時刻表示をするTextView
((TextView) findViewById(R.id.clock)).setText(nowDate);
}
});}
},0,1000);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 定期実行をcancelする
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
}