问题
I found this code in SO to show ProgressDialog
while load Activity
:
progDailog = ProgressDialog.show(MyActivity.this, "Process", "please wait....", true, true);
new Thread(new Runnable() {
public void run() {
// code for load activity
}).start();
Handler progressHandler = new Handler() {
public void handleMessage(Message msg1) {
progDailog.dismiss();
}
};
But I always get this exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I appreciate any help for this issue, thanks in advance.
回答1:
Here is what I would do,
AsyncTask to do the "heavy work" in background:
public class MyTask extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
public MyTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
//Do your loading here
return "finish";
}
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
//Start other Activity or do whatever you want
}
}
Start the AsyncTask:
MyTask myTask = new MyTask(this);
myTask.execute("parameter");
Of course you can change the generic types of the AsyncTask to match your problems.
回答2:
The problem is because you are trying to create Handler inside a worker Thread. It is not possible. Create your Handler inside of onCreate() or somewhere else on the main UI. And you can send message to your handler from your Worker Thread. This is because Android doesn't allow you to modify the UI from any other Thread other than the Main UI thread itself.
回答3:
You need to create your handler on the main thread rather than inside OnClick.
来源:https://stackoverflow.com/questions/10115403/progressdialog-while-load-activity