Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: listener that detects minute changing in the clock

Tags:

android

I am pondering over how to implement a listener as to detect whenever the minute passes on my phone.

1) Handler 2) AlarmManager 3) Own thread thing

I wish for my app to run specific code every minute the clock changes, it's important to fire the same time the minute changes on my phone, otherwise I would of just used a thread with wait 60000.

like image 695
basickarl Avatar asked Mar 09 '15 03:03

basickarl


2 Answers

Thanks to the hint of Manpreet Singh I was able to come up with the following:

BroadcastReceiver tickReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) {
            Log.v("Karl", "tick tock tick tock...");
        }
    }
};
registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK)); // register the broadcast receiver to receive TIME_TICK

Then call the following onStop():

// unregister broadcast receiver, will get an error otherwise
if(tickReceiver!=null) 
   unregisterReceiver(tickReceiver);
like image 199
basickarl Avatar answered Nov 02 '22 14:11

basickarl


Assuming that the method initClock() updates the UI, then I'd suggest the following:

private BroadcastReceiver mTimeTickReceiver;

@Override
protected void onResume() {
    super.onResume();
    initClock();

    mTimeTickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            initClock();
        }
    };
    registerReceiver(mTimeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mTimeTickReceiver);
}
like image 44
k2col Avatar answered Nov 02 '22 16:11

k2col