Skip to content Skip to sidebar Skip to footer

Showing Current Time In Android And Updating It?

I want to display current time and keep it updating, in this format example: 09:41 Hour:Minute. Is it possible to do in TextView? I tried some ways but I'm not getting what I actu

Solution 1:

Android has a view for this already.

http://developer.android.com/reference/android/widget/TextClock.html

You can use it directly in XML like so

<TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

It is min api 17, so you if need to go lower than that just look into

http://developer.android.com/reference/android/widget/DigitalClock.html

Worst case scenario you can subclass textview and steal the code from the textclock source. it should be fairly straightforward

Solution 2:

Something like this should do the trick

finalHandlersomeHandler=newHandler(getMainLooper());   
        someHandler.postDelayed(newRunnable() {
            @Overridepublicvoidrun() {
                tvClock.setText(newSimpleDateFormat("HH:mm", Locale.US).format(newDate()));
                someHandler.postDelayed(this, 1000);
            }
        }, 10);

You should keep a reference to the handler and the runnable to cancel this when the Activity goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null in onDestroy

Solution 3:

boolean run=true; //set it to false if you want to stop the timerHandler mHandler = newHandler();


 publicvoidtimer() {
        newThread(newRunnable() {
            @Overridepublicvoidrun() {
                while (run) {
                    try {
                        Thread.sleep(20000);
                        mHandler.post(newRunnable() {

                            @Overridepublicvoidrun() {
                                Calendar c = Calendar.getInstance();
                                int min = c.get(Calendar.MINUTE);
                                int hour=c.get(Calendar.HOUR);
                                TextView.setText(String.valueOf(hour)+":"+String.valueOf(min));
                            }
                        });
                    } catch (Exception e) {
                    }
                }
            }
        }).start();}

in the onCreate call it like this

timer();

Solution 4:

For someone who needing a custom date and time directly by using TextClock

  • Format for time: android:format12Hour="hh:mm:ss a"
  • Format for date: android:format24Hour="MMM dd, yyyy"
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_screenlock"
        app:layout_constraintStart_toStartOf="parent">

        <TextClock
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="60dp"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="70sp"
            android:format12Hour="hh:mm:ss a"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextClock
            android:id="@+id/textDateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@color/_white"
            android:textSize="28sp"
            android:format24Hour="MMM dd, yyyy"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
 </androidx.constraintlayout.widget.ConstraintLayout>


[![date_time_update_directly][1]][1]


  [1]: https://i.stack.imgur.com/JZWUj.png

Solution 5:

Why not use Java's Timer and TimerTask? They're very easy, reliable and simple to understand.

Here is an example:

publicclassClockCounterextendsTimerTask{

    privatelongtime= System.currentTimeMillis();

    @Overridepublicvoidrun(){
        time += 1000; //add 1 second to the time//convert ms time to viewable time and set MainActivity.text (textview) text to this.
    }

    publiclonggetTime(){ return time; }
}

publicclassMainActiviyextendsActivity{

    publicstatic TextView text;
    private Timer timer;

    @OverridepublicvoidonCreate(){
        //default code//set text view according to id
        timer = newTimer();
        timer.schedule(newClockCounter(), 0, 1000); //schedule clock counter to repeat every 1 seconds (1000 ms)
    }
}

I know there are some notes of what to do in there but any android developer with reasonable experience in Java should be able to figure out how to do those things.

I hope this helped!

EDIT To format the date to a viewable string, you can use the following code (also using only Java's shipped APIs)

Datedate=newDate();
DateFormatformatter=newSimpleDateFormat("HH:mm"); //Hourse:MinutesStringdateFormatted= formatter.format(date); //string representation

Post a Comment for "Showing Current Time In Android And Updating It?"