Reputation: 11
I'm new to android and have been doing some reading about worker threads and not blocking the UI thread. I'm playing around with a simple timer app that starts a thread that updates a textview every second when the activity is created. So my question is, these days what is the best way to do this. Both of the two examples below work but is there a better (more efficient/ more Android) way?
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
seconds++;
runOnUiThread(new Runnable() {
@Override
public void run() {
secondsTextView.setText(seconds);
}
});
handler.postDelayed(this, 1000);
}
}, 1000);
or
new Thread(){
@Override
public void run(){
try{
while(!isInterrupted()){
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
seconds++;
secondsTextView.setText(seconds);
}
});
}
}catch(Exception e){
Log.e("Activity1", e.toString());
}
}
}.start();
Upvotes: 0
Views: 1184
Reputation: 1006539
The more efficient way is:
timeOnTextView.postDelayed(new Runnable() {
@Override
public void run() {
seconds++;
timeOnTextView.postDelayed(this, 1000);
}
}, 1000);
The run()
of the Runnable
passed to postDelayed()
is invoked on the main application thread, so you do not need to use runOnUiThread()
.
Since postDelayed()
is implemented on View
, you do not need a Handler
.
Upvotes: 4