1

我在 doInBackground() 方法中执行了一项耗时的任务,但在该方法中,我希望能够使用百分比数据更新 progressDialog。我怎样才能做到这一点?

    class GetDataTask extends AsyncTask<Void, Void, Void> {     

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        //go get data, update mProgressDialog
        return null;
    }

    @Override
    protected void onPostExecute(Void res)
    {           

    }
}
4

2 回答 2

2

像这样覆盖 onProgressUpdate() 方法:

@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    mProgressDialog.setProgress(progress[0]);
}

并发布进度

publishProgress((int) (total * 100 / fileLength));

尝试参考这个链接

于 2012-07-26T01:29:42.647 回答
0

AsyncTask 具有方法onProgressUpdate(Integer...),您可以调用例如每次迭代或每次进度完成时doInBackground()通过调用publishProgress().

有关更多详细信息,请参阅文档


注意第二个参数是进度变量

class GetDataTask extends AsyncTask<Void, String, Void> {     

    @Override
    protected void onPreExecute()
    {
        mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        publishProgress(""+(int)count);
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        /**
         * Sets current progress on ProgressDialog
         */
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(Void res)
    {           

    }
}
于 2012-07-26T01:28:21.777 回答