How to use Intent.ACTION_TIME_TICK

1 Flares 1 Flares ×

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 com.cc.demo.digiClock

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 com.cc.demo.digiClock.DigiClockActivity has leaked IntentReceiver com.cc.demo.digiClock.DigiClockActivity$1@412bacb8 that was originally registered here. Are you missing a call to unregisterReceiver()?”

Happy Coding!!

Loading Disqus Comments ...