【问题标题】:Bitmap not caching?位图不缓存?
【发布时间】:2015-12-07 06:59:44
【问题描述】:

遇到从我的网络服务器加载个人资料图片所需时间过长的问题。这是我用来加载图像的代码(在 AsyncTask 中):

@Override
        protected Bitmap doInBackground(Void... params) {
            String urlPath = AppVariables.SERVER_ADDRESS + "pictures/" + name + ".JPG";
            try {
                URLConnection connection = new URL(urlPath).openConnection();
                connection.setUseCaches(true);
                connection.setConnectTimeout(1000 * 30);
                connection.setReadTimeout(1000 * 30);
                return BitmapFactory.decodeStream((InputStream) connection.getContent(), null, null);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

这应该根据这里的最佳答案工作:Android image caching

但我仍然遇到延迟 - 当我转到应用程序中的“个人资料”时,需要 2-3 秒才能显示个人资料图片。

有什么想法吗?

【问题讨论】:

    标签: android database caching bitmap


    【解决方案1】:
    //onCreate
    try
        {
            File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
            long httpCacheSize = 100 * 1024 * 1024; // 100 MiB
            HttpResponseCache.install(httpCacheDir, httpCacheSize);
        }
        catch (Exception e) {}
    
    //onStop
    try {
            HttpResponseCache cache = HttpResponseCache.getInstalled();
            if (cache != null) {
                cache.flush();
            }
        }
        catch(Exception e){}
    

    你在设置你的缓存吗?

    【讨论】:

    • 我不是,但我尝试了您的缓存解决方案,但仍然遇到延迟。
    【解决方案2】:

    只需使用通用图像加载器 (https://github.com/nostra13/Android-Universal-Image-Loader)。

    您可以像这样设置缓存图像:

    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheOnDisk(true)
                .build();
    

    然后,您可以像这样获取缓存图像的 URL:

    File file = DiscCacheUtil.findInCache(imageUrl, imageloader.getDiscCache());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多