Android
How to use Timer and TimerTask 타이머 사용하기
J-sean
2019. 10. 9. 17:34
반응형
Timer와 TimerTask를 이용해 정해진 시간에 반복적인 작업을 할 수 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class MainActivity extends AppCompatActivity { TextView textView; Timer timer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd EEE HH:mm:ss"); TimerTask timerTask = new TimerTask() { @Override public void run() { // Only the original thread that created a view hierarchy can touch its views. runOnUiThread(new Runnable() { @Override public void run() { String currentTime = simpleDateFormat.format(new Date()); textView.setText(currentTime); } }); } }; timer = new Timer(); timer.schedule(timerTask, 0, 1000); } @Override protected void onDestroy() { timer.cancel(); super.onDestroy(); } } |
반응형