I am creating a custom watch face for android by following this tutorial. I have implemented broadcast receiver to detect change in time as follows:
Inside my activity I have static block to filter following intents:
static {
intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_TICK);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
}
My receiver class:
public class MyReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
c = Calendar.getInstance();
Log.d("myapp", "time changed");
hrs = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
sec = c.get(Calendar.SECOND);
txt_hrs.setText(String.valueOf(hrs));
txt_mins.setText(String.valueOf(min));
txt_sec.setText(String.valueOf(sec));
}
}
And I have registered receiver inside oncreate():
MyReciever myReciever = new MyReciever();
registerReceiver(myReciever,intentFilter);
Above code works fine for hours and minutes, but doesn't work for seconds.
the problem with Intent.ACTION_TIME_TICK
is that it is broadcasted each minute, not second.
I need to detect change in time each second for the clock on watchface. Anyone have any solution for 'detecting time change per second'?
You may look why you are not getting intent after every seconds. So better is to create a separate thread or use asynctask where you need to update your textview on each one seconds.
Or you can use Timer
and TimerTask
for such purpose, like below
public void updateTimeOnEachSecond() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
c = Calendar.getInstance();
Log.d("myapp", "time changed");
hrs = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
sec = c.get(Calendar.SECOND);
runOnUiThread(new Runnable() {
@Override
public void run() {
txt_hrs.setText(String.valueOf(hrs));
txt_mins.setText(String.valueOf(min));
txt_sec.setText(String.valueOf(sec));
}
});
}
}, 0, 1000);
}
And call this method after initialising each view from activity.