dong221 dong221 - 1 month ago 24
Android Question

Date and time change listener in Android?

In my application, there's a alarm service, and I find that if user change it's date or time to a passed time. My alarm will not be triggered at the time I expect.

So, I may have to reset all the alarms again. Is there an date and time change listener in android?

Answer

Create an intent filter :

     static {
        s_intentFilter = new IntentFilter();
        s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
        s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
    }

and a broadcast receiver:

    private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(Intent.ACTION_TIME_CHANGED) ||
                action.equals(Intent.ACTION_TIMEZONE_CHANGED))
            {
                doWorkSon();
            }
        }
    };

register the receiver:

     public void onCreate() {
        super.onCreate();
        registerReceiver(m_timeChangedReceiver, s_intentFilter);     
    }

EDIT:

and unregister it:

     public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(m_timeChangedReceiver);     
    }