Android 使用asynctask和progressbar下载文件
我有以下代码来下载图像,显示进度条并返回位图。但是位图总是返回null。。一旦我删除while循环,位图就有了值,但是我没有得到进度条Android 使用asynctask和progressbar下载文件,android,Android,我有以下代码来下载图像,显示进度条并返回位图。但是位图总是返回null。。一旦我删除while循环,位图就有了值,但是我没有得到进度条 @Override protected Bitmap doInBackground(String... params) { bitmap = null; try { URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConne
@Override
protected Bitmap doInBackground(String... params) {
bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = connection.getInputStream();
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
Log.e("could not load ", e.getMessage());
e.printStackTrace();
return null;
}
}
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
public void onPostExecute(Bitmap result) {
pDialog.dismiss();
listener.onTaskCompleted(result);
}
enter code here
您不需要接口,因为asynctask可以返回位图
private class DownloadFilesTask extends AsyncTask<String, Integer, Bitmap> {
protected Bitmap doInBackground(String... params) {
return downloadBitmap();
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
InputStream只能读取一次。您需要将代码更改为:
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
String pathName=Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
不应该使用get,它会挂起UI。这不是一个很长的挂起时间,可能是300毫秒,get只调用onPost方法,onPost在主线程上运行,所以挂起是正常的。如果你不想挂起UI,可以打开新线程!AsyncTask在不同的线程上运行。使用onPostExecute时不会出现任何挂起。你怎么能如此肯定300毫秒?这取决于所访问的内容,对吗?使用get是不好的做法,它取决于正在访问的内容。正在访问的内容是一个位图,我相信它不会超过300毫秒,所以用户无法捕获它。没有人谈论界面。实际上,在异步任务上使用get是一个非常糟糕的主意。在BitmapFactory.decodeStreaminput之前,您需要重置inputstream或重新打开它。您可以使用ProgressDialog?代替ProgressBar吗?。我觉得长头发有点问题。请发布exceptionsSkImageDecoder::Factory返回空值,仅此项在logcat中显示,在运行progressbar后,此设备中没有显示任何内容。当我调试时,我可以看到,在位图deocde之后,编译器将在catch{}中返回null
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
String pathName=Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathName);