13

I need to display the current time in a textview and the time changes dynamically for every second (Like the digital clock) in android.. I have googled but i didnt get the help.If Anyone have the idea for this, please help me Thanks in advance.

Navamani Samuel
  • 558
  • 2
  • 4
  • 15
  • Possible duplicate of [Showing current time in Android and updating it?](https://stackoverflow.com/questions/29952404/showing-current-time-in-android-and-updating-it) – Majid Ali Aug 28 '19 at 21:50

6 Answers6

25

This is the Code..

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Thread myThread = null;

    Runnable myRunnableThread = new CountDownRunner();
    myThread= new Thread(myRunnableThread);   
    myThread.start();

}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.myText);
                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    txtCurrentTime.setText(curTime);
            }catch (Exception e) {}
        }
    });
}


class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                doWork();
                    Thread.sleep(1000); // Pause of 1 Second
                } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}
Bhavin
  • 5,572
  • 4
  • 21
  • 26
  • I'm quite wondering how to implement this using Fragments. On this one, I'm having an error in... runOnUiThread(new Runnable() { – princepiero Aug 12 '13 at 09:19
  • It is working like awesome,But i need to kill the thread when activity stops.How to do that. – user Nov 06 '13 at 10:00
  • 2
    @user : use thread.interrupt() whenever you want to want to stop Thread. If you want to kill thread when your activity stops then you can add it to Activity's overriden method stop or destroy. – Bhavin Nov 07 '13 at 06:45
16

Use TextClock. this wil change dynamically without having a separate code.

        <TextClock
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/textClock"
            android:layout_weight="0.11"
            android:textStyle="bold"
            android:textSize="22sp"
            android:format24hours="hh:mm:ss a  EEE MMM d"/>

    TextClock textClock = (TextClock) findViewById(R.id.textClock);
    textClock.setFormat12Hour(null);
    //textClock.setFormat24Hour("dd/MM/yyyy hh:mm:ss a");
    textClock.setFormat24Hour("hh:mm:ss a  EEE MMM d");
Nikhil Dinesh
  • 3,029
  • 2
  • 34
  • 39
14

Use CountDownTimer class , pass a huge value to (here I gave 1000000000) for CountDownTimer life .

Sample Code::

CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) { 

            public void onTick(long millisUntilFinished) {
                Calendar c = Calendar.getInstance();
                textView.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
            }
            public void onFinish() {

            }
        };
        newtimer.start();

While closing the Activity, call the following function

newtimer.cancel();
Ayyappan
  • 1,179
  • 1
  • 10
  • 24
6

You can use Thread Class with sleep(1000); or you can use TimerTask Class.

Lucifer
  • 28,605
  • 21
  • 86
  • 137
5

Use Chronometer class in Android.

robert
  • 29,284
  • 8
  • 50
  • 70
Gaurav Agarwal
  • 17,165
  • 28
  • 97
  • 157
2

for this you should try Chronometer, by this you can fulfill your goal good luck

sample code of Chronometer is here :

in main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<Chronometer
 android:id="@+id/chronometer"
 android:layout_gravity="center_horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
 />
<Button
 android:id="@+id/buttonstart"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Start"
 />
<Button
 android:id="@+id/buttonstop"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Stop"
 />
<Button
 android:id="@+id/buttonreset"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Reset"
 />
</LinearLayout>

in java file

package com.exercise.AndroidChronometer;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class AndroidChronometer extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
       Button buttonStart = (Button)findViewById(R.id.buttonstart);
       Button buttonStop = (Button)findViewById(R.id.buttonstop);
       Button buttonReset = (Button)findViewById(R.id.buttonreset);

       buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.start();
   }});

       buttonStop.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.stop();

   }});

       buttonReset.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime());

   }});


   }
}
Dhruvil Patel
  • 2,836
  • 2
  • 20
  • 39