• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Constantly repeat code

I'm trying to add a clock into my app and I need some code to be constantly running to get the current time. is there a simple way of making code constantly run?
 
I'm trying to add a clock into my app and I need some code to be constantly running to get the current time. is there a simple way of making code constantly run?
I've done something similar in the past using a Thread that refreshes every second.
Here's a sample to give you an idea.
Java:
Thread thread = new Thread() {
    public void run() {
        try {
            while (!isInterrupted()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Run your clock code here in a TextView
                        // Example:
                        tv.setText(""+((System.currentTimeMillis() - startTime)/1000));
                    }
                });
                Thread.sleep(1000); // This refreshes the thread once every second. Adjust as needed.
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread.start();
Just do a search for threading in android to find tutorials.
 
Back
Top Bottom