I created an AsyncTask
to perform my background operation. The UI shows a ProgressDialog
. I pass the Conte开发者_Go百科xt
to the constructor of the AsyncTask
.
When I want to manipulate the the ProgressDialog
text from AsyncTask
it errors because the ProgressDialog
box is created by a different thread.
Tips or ideas on how I can make the AsyncTask
communicate with the ProgressDialog
box, or a better way to create the ProgressDialog
box?
You shouldn't communicate with UI from AsyncTask
's doInBackground
function. Use onProgressUpdate
function instead.
private class BackgrounTask extends AsyncTask<Integer, Integer, Integer> {
protected Integer doInBackground(Integer... count){
int max = count[0];
for (int i = 0; i < count; i++) {
publishProgress(i, max);
}
return max;
}
protected void onProgressUpdate(Integer... progress) {
int cur = progress[0];
int max = progress[1];
//update your progress dialog here
}
protected void onPostExecute(Integer result) {
//process result
}
}
Use AsyncTask.publishProgress()
method and override AsyncTask.onProgressUpdate()
method. In this method update your progress dialog.
精彩评论