Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android thread problem, why ui still blocks when i have used a worker thread?

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...

like image 473
shanqn Avatar asked Oct 17 '10 06:10

shanqn


1 Answers

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.

like image 163
eSniff Avatar answered Oct 13 '22 11:10

eSniff