Question:
Good day, everyone. There is a need for the title of my ActionBar
in the Activity
change every minute. The time of the mm:ss
format should be displayed there. Naturally, I will not deal with such a process in the main thread, and I created a separate one. But this command
getSupportActionBar().setTitle(new SimpleDateFormat("mm:ss").format(new Date(this.time)));
requires me to run it on the main thread, and not in any other, since an Exception
. I dug around on the Internet, where I was told what can be done this way
runOnUiThread(new Runnable() {
@Override
public void run() {
getSupportActionBar().setTitle(new SimpleDateFormat("mm:ss").format(new Date(this.time)));
}
});
But, unfortunately, this option is not very good. By the fortieth minute, my application crashed for an unknown reason. I figured out the logs, and found out that it takes too many milliseconds to run the runOnUiThread
, after which this command was simultaneously run twice. I noticed that my title changes unevenly. After all, it should be updated after 1000 ms, which means a second, and then 900 ms, then 1200 ms, and so on, are updated. What is the reason for this, I do not know. How to solve the problem so that the title changes exactly every 1000ms?
I ask you not to suggest that I simply not use the title, but create some kind of my own, for example, a TextView
in the Activity
. Also, a bad option is getSupportActionBar().setCustomView(...)
as described here .
Answer:
What about a Handler that allows deferred code execution? Here's an example:
private final int ONE_SECOND = 1000;
private Handler mHandler = new Handler();
private Runnable timeUpdaterRunnable = new Runnable() {
@Override
public void run() {
//тут что нибудь делается
};
And here is the launch of the deferred task:
mHandler.postDelayed(this, ONE_SECOND);