It's gonna be a pretty good amount of code to add, but, here's what you have to do.
Assuming that you have a class extending Activity
, you'll need to override onPause()
and onResume()
.
For example:
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
In these two methods, you are going to have to register and unregister an IntentFilter
.
Create the IntentFilter
as a global variable. We'll also create the listener that'll be used later.
private IntentFilter filter;
private final BroadcastReceiver listener;
Instantiate it in your onCreate()
.
filter = new IntentFilter();
filter.addAction(Intent.ACTION_DATE_CHANGED);
Also, directly after that, we'll create the listener to tell it what to do when the date changes.
listener = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
TextView tv = (TextView) findViewById(R.id.date);
String ct = DateFormat.getDateInstance().format(new Date());
tv.setText(ct);
}
};
Finally, we have to register and unregister the listener when the app opens and closes.
@Override
protected void onResume() {
super.onResume();
registerReceiver(listener, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(listener);
}
And, there you have it! Should automatically update when the date changes now. Also, I wouldn't recommend re-initializing the TextView
every time the date changes, but your current code was that, so I left it.
More info from Ben English