Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and time change listener in Android?

Tags:

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?

like image 994
dong221 Avatar asked Mar 30 '11 02:03

dong221


2 Answers

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);     
}
like image 128
Ben English Avatar answered Nov 20 '22 08:11

Ben English


In addition to the accepted answer

If you want to listen to time changes while your app is not running I would register in the manifest:

<receiver android:name="com.your.pacakge.TimeChangeBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.TIME_SET"/>
        <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
    </intent-filter>
</receiver>

If you do this, do not explicitly register the receiver in the code with registerReceiver and unregisterReceiver.

Again, this is just an addition to the accepted answer.

like image 32
Chad Bingham Avatar answered Nov 20 '22 08:11

Chad Bingham