views:

53

answers:

1
package com.commonsware.android.threads;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class HandlerDemo extends Activity {
   Thread mBackground;
   ProgressBar bar;
    Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                    bar.incrementProgressBy(5);
            }
    };
    boolean isRunning = false;

    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            bar = (ProgressBar) findViewById(R.id.progress);
    }

    public void onStart() {
            super.onStart();
            bar.setProgress(0);

            mBackground = new Thread(new Runnable() {
                    public void run() {
                            try {
                                    int a = 0;
                                    for (int i = 0; i < 20 && isRunning; i++) {
                                            for (int j = 0; j < 2000; j++) {
                                                    for (int k = 0; k < 1000; k++) {
                                                            a++;
                                                    }
                                            }
                                            handler.sendMessage(handler.obtainMessage());
                                    }
                            } catch (Throwable t) {
                                    // just end the background thread
                            }
                    }
            });

            findViewById(R.id.LoginButton).setOnClickListener(
                            new OnClickListener() {
                                    public void onClick(View v) {
                                            mBackground.run();
                                    }
                            });

            isRunning = true;

    }

    public void onStop() {
            super.onStop();
            isRunning = false;
    }

}

I'm really confused about that...

+1  A: 

You need to call start() not run().

public void onClick(View v) {
      mBackground.start();  //Start will spawn the Thread and then call it's run method.
}

By calling run() in the main thread, you are blocking there just like any normal method call.

eSniff
Sorry I edited that answer a few times trying to figure out how much to say or not. In the end I decided to only comment on the answer. Good luck.
eSniff