我在我的项目中使用的缩略图加载器如下。问题在于,它会正确加载所有缩略图,但大小约为40K的缩略图除外。当我们的后端给出此类缩略图时,有时不会最终导致崩溃。

我应该怎么办?

public class ThumbnailManager
{

private final Map<String, Bitmap> drawableMap;
public static Context context;
private Resources res;
private int thumbnail_size;

public ThumbnailManager()
{
    drawableMap = new HashMap<String, Bitmap >();
    res = new Resources(context.getAssets(), null, null);
    thumbnail_size = res.getInteger(R.ThumbnailManager.THUMBNAIL_SIZE);
}

public Bitmap fetchBitmap(String urlString)
{
    if(drawableMap.containsKey(urlString))
    {
        return (drawableMap.get(urlString));
    }

    //Log.d(getClass().getSimpleName(), " Image URL :: "+ urlString);
    try
    {
        InputStream is = fetch(urlString);
        android.util.Log.v("ThumbnailManager", "ThumbnailManager " + urlString);
        drawableMap.put(urlString, BitmapFactory.decodeStream(is));//Bitmap.createScaledBitmap(BitmapFactory.decodeStream(is), thumbnail_size, thumbnail_size, false));
        return drawableMap.get(urlString);
    }
    catch(Exception e)
    {
        android.util.Log.v("EXCEPTION", "EXCEPTION" + urlString);
        return null;
    }
}

public void fetchBitmapOnThread(final String urlString, final ImageView imageView)
{
    if(drawableMap.containsKey(urlString))
    {
        imageView.setImageBitmap(drawableMap.get(urlString));
        return;
    }

    if(urlString.compareTo("AUDIO") == 0)
    {
        Bitmap audioThumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.timeline_audio_thumb);
        drawableMap.put(urlString, Bitmap.createScaledBitmap(audioThumb, thumbnail_size, thumbnail_size, false));
        imageView.setImageBitmap(drawableMap.get(urlString));
        return;
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message message)
        {
            imageView.setImageBitmap((Bitmap) message.obj);
        }
    };

    Thread thread = new Thread()
    {
        public void run()
        {
            Bitmap urlBitmap = fetchBitmap(urlString);
            Message message = handler.obtainMessage(1, urlBitmap);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

public InputStream fetch(String urlString) throws IOException, MalformedURLException
{
    final URL url = new URL(urlString);
    final URLConnection conn = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) conn;
    httpConn.setAllowUserInteraction(true);
    httpConn.setInstanceFollowRedirects(true);
    httpConn.setRequestMethod("GET");
    httpConn.connect();

    return(conn.getInputStream());
}
}

最佳答案

如果您在此处添加了stacktrace,那就太好了。但是我也怀疑它是内存问题。如果要将大量位图加载到内存中,则它们比原始文件大小需要更多的内存。例如您的40k缩略图可以作为位图为400k,具体取决于分辨率。使用ddms并查看您的应用程序有多少可用内存。如果它获得的工作内存少于2MB,则在解码大拇指时,BitmapFactory很可能会产生RuntimeException。

关于android - Android缩略图加载问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2477294/

10-13 09:48