I’m trying to understand the code here , specifically the anonymous class
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postAtTime(this,
start + (((minutes * 60) + seconds + 1) * 1000));
}
};
The article says
The Handler runs the update code as a part of your main thread, avoiding the overhead of a second thread..
Shouldn’t creating a new Runnable class make a new second thread? What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?
Thanks
Runnableis often used to provide the code that a thread should run, butRunnableitself has nothing to do with threads. It’s just an object with arun()method.In Android, the
Handlerclass can be used to ask the framework to run some code later on the same thread, rather than on a different one.Runnableis used to provide the code that should run later.