How to use Intent.ACTION_TIME_TICK

In one of my applications, it was required to update a TextView every minute. The first approach that I could think of was to have an AsyncTask running a while loop till a minute (check for initial time+60,000 milliseconds in every iteration), but then I found out about ACTION_TIME_TICK broadcast action.

As per java docs:-

public static final String ACTION_TIME_TICK

Broadcast Action: The current time has changed. Sent every minute. You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

This is a protected intent that can only be sent by the system.

Note: It is assumed that reader has knowledge of how to create and run a simple android application.

To learn how to use this broadcast action, I made a small program to display the current time (hours and minutes) in the form of a digital clock. The process is as follows:-

  1. Create a new Android project, with name DigiClock and package name

Open activity_main.xml and paste the following:

3. Open Activity class(create one if already not created) and paste the following:-

In the above code, we first create a broadcast receiver object, which will change the text of our TextView when the received action is ACTION_TIME_TICK. After that, we register this broadcast receiver via call to registerReceiver, which calls “tickReceiver” with any broadcast intents that matches “ACTION_TIME_TICK” i.e. the onReceive method of tickReceiver will be called every minute.

Note: Do remember to call the method “unregisterReceiver” or else your application will throw an exception like this:-

“Activity has leaked IntentReceiver$1@412bacb8 that was originally registered here. Are you missing a call to unregisterReceiver()?”

Happy Coding!!