Universal Image loader fails to load images sometimes

后端 未结 2 809
死守一世寂寞
死守一世寂寞 2021-02-04 12:54

I\'m using universal image loader and I get quite large numbers of images failing to load for users every day. I\'m using this code to get my errors to analytics.



        
2条回答
  •  心在旅途
    2021-02-04 13:10

    failReason.getType() can't be null but failReason.getCause() can. You should check it to prevent NPE.

    failReason.getCause() can be null if you deny network by ImageLoader.denyNetworkDownloads(true) or if decoding error occurred. This is because Android can't decode image by some reason.

    BTW I recommend you to use .cacheOnDisc() even for big images (options2). And maybe try other memory cache implementation? E.g. LruMemoryCache.

    I don't know the reason of java.io.EOFException but can you detect which network is used in that time? Mobile or WiFi? Maybe try use ImageLoader.handleSlowNetwork(boolean) to switch between network types.

    UPD: Also try to reduce thread pool size. Maybe it helps to prevent DECODING ERRORS. UPD2: Decoding error can be caused by web site redirect to web page. You can try extend BaseImageDownloader and add empty string for "User-Agent" header in request.

    public class MyImageDownloader extends BaseImageDownloader {
    
    private static final int MAX_REDIRECT_COUNT = 5;
    
    public MyImageDownloader(Context context) {
        super(context);
    }
    
    protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
        HttpURLConnection conn = connectTo(imageUri);
    
        int redirectCount = 0;
        while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
            conn = connectTo(conn.getHeaderField("Location"));
            redirectCount++;
        }
    
        return new BufferedInputStream(conn.getInputStream(), BUFFER_SIZE);
    }
    
    protected HttpURLConnection connectTo(String url) throws IOException {
        String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
        HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();
        conn.setConnectTimeout(connectTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setRequestProperty("User-Agent", "");
        return conn;
    }
    }
    

    Or since UIL 1.8.5:

    public class MyImageDownloader extends BaseImageDownloader {
        @Override
        protected HttpURLConnection createConnection(String url) throws IOException {
            HttpURLConnection conn = super.createConnection(url);
            conn.setRequestProperty("User-Agent", "");
            return conn;
        }
    }
    

提交回复
热议问题