gpt4 book ai didi

java - 无法发布后台 while 循环中异步任务的进度 - Android

转载 作者:太空宇宙 更新时间:2023-11-04 13:09:22 26 4
gpt4 key购买 nike

我想从 doInBackground 更新对话框的下载进度。
我正在打印日志并发布进度。
他们都没有工作。

它最后更新对话框并最后一次打印所有日志值

private class DownloadEReport extends AsyncTask<String, Void, Void> {
int progress = 0;

protected void onPreExecute() {
mProgressDialog = new ProgressDialog(EReport.this);
mProgressDialog.setTitle("Downloads");
mProgressDialog.setMessage("Downloading, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mProgressDialog.setProgress(progress);
}



@Override
protected Void doInBackground(String... strings) {

String mUrl = strings[0];
String json = "";
int count;
try {
URL url = new URL(mUrl);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);

// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.txt");

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);

// publishing the progress....
// After this onProgressUpdate will be called
Log.e("JSON Download Progress", "" + (int) ((total * 100) / lenghtOfFile));
progress = (int) (total * 100 / lenghtOfFile);
publishProgress();
}

// flushing output
output.flush();
// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
}
}

最佳答案

从 onProgressUpdate 中删除 super 然后尝试

@Override
protected void onProgressUpdate(Void... values) {
//super.onProgressUpdate(values);
mProgressDialog.setProgress(progress);
}

如果它不起作用,请在循环中添加 sleep 语句,以便该循环释放处理器并有时间发布进度

try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}

关于java - 无法发布后台 while 循环中异步任务的进度 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34134013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com