Search code examples
androidtimetextview

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 actually want.


Solution

  • Something like this should do the trick

    final Handler someHandler = new Handler(getMainLooper());   
            someHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
                    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