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
No. new Runnable does not create second Thread .
You can create a new thread simply by extending your class from Thread and overriding it's run() method. The run() method contains the code that is executed inside the new thread. Once a thread is created, you can start it by calling the start() method. Thread.
Runnable
is often used to provide the code that a thread should run, but Runnable
itself has nothing to do with threads. It's just an object with a run()
method.
In Android, the Handler
class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable
is used to provide the code that should run later.
If you want to create a new Thread
...you can do something like this...
Thread t = new Thread(new Runnable() { public void run() {
// your code goes here...
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With