问题
While I'm updating my database I want to display a progress dialog. My problem is that the ProgressDialog is getting late to appear,after 4-5 seconds, then appears and disappears very fast, it stays on screen few milliseconds almost you can't see it, then new data are shown in the list immediately. This makes me think that the ProgressDialog is waiting for database to be updated(it doesn't take much, about 4,5 seconds) and then it shows on the screen but is dismissing very fast. I would like the ProgressDialog appear immediately I press the 'Update' button and stay on the screen about 4-5 seconds.
class MyAsyncTask extends AsyncTask<Void, Void, Void>{
ProgressDialog myprogsdial;
@Override
protected void onPreExecute(){
myprogsdial = ProgressDialog.show(MyActivity.this, null, "Upgrade", true);
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
RefreshDataBase();
}
});
return null;
}
@Override
protected void onPostExecute(Void result){
myprogsdial.dismiss();
}
}
When I call it, new MyAsyncTask().execute();
回答1:
Ok I think that this
runOnUiThread(new Runnable() {
is causing this behavior.
doInBackground() executes your code in a new thread to the main UI thread. You are then putting the code to execute in this thread back into the main one causing the progress dialog to be delayed at the end and then in postExecute() it gets closed immediately.
A good asyntask tutorial can be found here.
回答2:
You must not use runOnUiThread
. What you're basically did is:
- Started new non-ui thread
- From this new non-ui thread you posted a long running task to UI thread.
- Exited from non-ui thread.
- Your ui thread now executes long-running operation (
RefreshDataBase
) and blocks the UI.
You should call RefreshDataBase()
directly. And if this method touches UI, you have to refactor it.
回答3:
I have solved it, using this answer of Vladimir Ivanov.
I have separated the functionality by the appearance.
I have kept the functionality(downloading new data) in doInBackground()
and in onPostExecute()
I updated the list: get the new adapter,called setListAdaper()
and notifyDataSetChanged
.
Of course, I quit using runOnUiThread()
. Thanks to all for hints.
来源:https://stackoverflow.com/questions/8823365/progressdialog-appears-too-late-and-dissapears-too-fast