【问题标题】:Android- Downloading Images occasionally fails.Android- 下载图像偶尔会失败。
【发布时间】:2015-01-04 12:18:41
【问题描述】:

我正在尝试在我的 android 应用程序中从网上下载图像,它在大多数情况下都能正常工作,但有些图片无法下载并且位图为空。但是,图像的链接始终存在。任何想法是什么原因造成的?

     private class GetImage extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {

                int len = 500;

                try {
                    URL url = new URL(urls[0]);
                    Log.v("url",urls[0]);
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    connection.setReadTimeout(10000);
                    connection.setConnectTimeout(15000);
                    connection.setRequestMethod("GET");
                    connection.setDoInput(true);

                    connection.connect();
                    int response = connection.getResponseCode();

                    inputstream = connection.getInputStream();
                    System.out.println(inputstream.toString());

                    bitmap = BitmapFactory.decodeStream(inputstream);
                    if(bitmap==null)
                        Log.v("Bitmap","fail");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (inputstream != null) {
                        try {
                            inputstream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                return "some string since it bitmap is sometimes null";

【问题讨论】:

    标签: android android-activity android-asynctask


    【解决方案1】:

    您不能总是依赖网络。您可以使用像 okhttp 或 volley 这样的 http 库,它可以让您轻松地进行重试(或者您可以自己重试)。这些库做了很多事情来平滑使用原始 HttpUrlConnection 的 http 体验。

    根据图像的重要性,如果图像失败,您始终可以将图像隐藏在 onPostExecute 中。

    【讨论】:

    • 不,每次都是相同的图像,如果我更改图像它可以正常工作。而且我现在无法重试另一个库,截止日期快到了。
    • 虽然它和其他所有文件一样都是 JPG
    • 当您尝试下载这些图像时,您是否遇到了特定的异常?
    • 一点也不。我觉得很奇怪。
    • 如果您从浏览器转到 url,图像是否正确显示?
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2015-03-26
    • 2013-03-03
    • 2014-10-14
    相关资源
    最近更新 更多