Android - Handler

Now the result is more like a progress bar, so when you click it goes from the left to the right using

An instance of Handler class created in a scope of the main thread can update the user interface. For instance, if you create new instance of Handler class in onCreate() method of your Activity, this handler will be assigned to the main thread and therefore all runnable tasks posted to this handler can update the user interface. The Handler class provides methods for receiving instances of the Message or Runnable class.

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
private Handler handler;
private ProgressBar progress;
private TextView text;

/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {
progress = (ProgressBar) findViewById(;
text = (TextView) findViewById(;


public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
} catch (InterruptedException e) {
Log.e("debug", Integer.toString(i));
if (i == 10)
Log.e("debug", "Finish");
} Runnable() {
public void run() {
new Thread(runnable).start();


Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]