开发者

Android 2.2 - Downloading only every 2 files - other one fails

I'm a newbie at Android, and developing my first app.

I'm using the following code to download 10 images from my website

private class DownloadImages extends AsyncTask<Integer, Integer, Integer> {

    @Override
    protected Integer doInBackground(Integer... pic_ids){

        int count = pic_ids.length;
        for (int i = 0; i < count; i++) {

            // download the image fro开发者_如何学Gom website ...
            String url = "http://www.mysite.com/pic.php?pid=" + pic_ids[i];
            DownloadFromUrl(url, pic_ids[i] + ".jpg");
            publishProgress((int) (i + 1));
        }

        return count;
    }
}

public void DownloadFromUrl(String imageURL, String fileName){

    try {
        URL url = new URL(imageURL);
        File file = new File(getFilesDir() + "/" + fileName);

        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is, 8192);

        ByteArrayBuffer baf = new ByteArrayBuffer(128);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e);
    }

}

The "DownloadImages" is passed an array of 10 ID's. All are handled (I have Log.d statements in between to check), however, only 1 out of 2 actually gets downloaded. Not in a random way: the first one is downloaded, the second one not, the third one is downloade, the fourth not etc. That means: The files are all written to the phone/emulator, but those that "fail" are empty.

When I start it again with only the 5 remaining images (those that were not downloaded the first time), the same thing happens (1st one downloaded, 2nd one not, ...)

I don't see an error in the logs. Adding a check for baf.length shows that this is 0 for those files that fail.

Any idea ?


This is long past due but I was having the same issue a few months ago. The strange thing was it only happened while connecting with SSL.

I eventually had to implement a checker to see if it truly downloaded and if not tried again (terminated after the second attempt at each file).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜