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;
}
}
我真的困惑关于那个......
答案 0 :(得分:39)
你需要调用start()而不是run()。
public void onClick(View v) {
mBackground.start(); //Start will spawn the Thread and then call it's run method.
}
通过在主线程中调用run(),就像任何正常的方法调用一样阻塞它。
答案 1 :(得分:0)
试试这段代码
private void showProgrssBar(){
pLayout.setVisibility(View.VISIBLE);
final StringBuffer s=new StringBuffer();
final Thread progressThread=new Thread(){
@Override
public void run(){
while(CreateVideoService.processingFrame>1) {
inc=100-((CreateVideoService.processingFrame*100)/(CreateVideoService.numberofRecordedFrames));
if(s.length()>0)
s.delete(0, s.length());
s.append("Processing... ").append(inc).append("%");
progressBarHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
progressBar.setProgress(inc);
textProgrs.setText(s);
}
});
//progressBar.setProgress(100-inc);
try {
// Sleep for 5 seconds
Thread.sleep(200);
} catch (InterruptedException e) {
//Log.d("TAG", "sleep failure");
}
}
layoutHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pLayout.setVisibility(View.GONE);
}
});
}
};
progressThread.start();
}