Skip to content

Instantly share code, notes, and snippets.

@arkty
Created October 20, 2016 16:04
Show Gist options
  • Save arkty/e5bd017784d070eaec52994f3258e6ac to your computer and use it in GitHub Desktop.
Save arkty/e5bd017784d070eaec52994f3258e6ac to your computer and use it in GitHub Desktop.
package com.example.beginner1;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class ClockActivity extends AppCompatActivity {
private TimerProcessor timerProcessor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock);
timerProcessor = new TimerProcessor(new Handler(),
(TextView) findViewById(R.id.clockView));
}
@Override
protected void onStart() {
super.onStart();
timerProcessor.start();
}
@Override
protected void onStop() {
super.onStop();
timerProcessor.stop();
}
public static class TimerProcessor implements Runnable {
private static final SimpleDateFormat CLOCK_FORMAT
= new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
private final Handler handler;
private final TextView view;
public TimerProcessor(Handler handler, TextView view) {
this.handler = handler;
this.view = view;
}
public void start() {
this.handler.post(this);
}
public void stop() {
this.handler.removeCallbacks(this);
}
@Override
public void run() {
Date date = new Date();
this.view.setText(CLOCK_FORMAT.format(date));
this.handler.postDelayed(this, 1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment