我试图在我的应用程序中显示进度条,但遇到线程问题。这是我用来执行此操作的代码:
package com.integrated.mpr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Progess extends Activity {
static String[] display = new String[Choose.n];
private static final int Progress = 0;
ProgressBar bar;
TextView label;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
bar = (ProgressBar) findViewById(R.id.progBar);
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i++;
}
});
}
}
private int doWork() {
display = new Logic().finaldata();
return i * 3;
}
}).start();
Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST");
startActivity(openList);
}
}
我收到以下 logcat 消息:
05-30 12:38:00.082: E/AndroidRuntime(17332): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
请帮助我,我是线程新手。
最佳答案
与其以这种方式实现线程,我建议您实现 AsyncTask 被称为 Painless Threading在 Android 中。
- 在
onPreExecute()
中显示进度条 - 在
doInBackground()
中执行后台任务
- 关闭
onPostExecute()
中的进度条 - 在
onProgressUpdate()
内更新进度条
关于Android - 显示进度条时出现 'Cant create handler' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811777/