使用asynctask下载文件并显示进度条

时间:2014-08-12 06:50:56

标签: android

我有以下代码来下载图像,显示进度条并返回其位图。但是位图总是返回null ..一旦我删除了while循环,位图就有了值,但是我没有得到进度条。

@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

2 个答案:

答案 0 :(得分:0)

你不需要接口,因为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);
 }

调用任务时,必须使用get();

Bitmap bitmap = new DownloadFileTask().execute().get();

答案 1 :(得分:0)

一个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);