2

我对 J2ME 上的概念并不陌生,但我有点懒惰,我不应该这样做:最近我的应用程序一直在将图像加载到内存中,因为它们是糖果......

Sprite example = new Sprite(Image.createImage("/images/example.png"), w, h);

我不确定这是不是最好的方法,但它在我的摩托罗拉 Z6 上运行良好,直到昨晚,当我在旧三星手机上测试应用程序时,图像甚至无法加载,需要多次尝试启动线程出现。屏幕一直是白色的,所以我意识到它必须是关于图像加载的东西,我做得不太好......有没有人可以告诉我如何在我的应用程序中正确地制作加载程序?

4

3 回答 3

4

I'm not sure exactly what you are looking for, but the behavior you describe very much sounds like you are experiencing an OutOfMemory exception. Try reducing the dimensions of your images (heap usage is based on dimension) and see if the behavior ceases. This will let you know if it is truly an OutOfMemory issue or something else.

Other tips:

  1. Load images largest to smallest. This helps with heap fragmentation and allows the largest heap space for the largest images.
  2. Unload (set to null) in reverse order of how you loaded and garbage collect after doing so. Make sure to Thread.yield() after you call the GC.
  3. Make sure you only load the images that you need. Unload images from a state that the application is no longer in.
  4. Since you are creating sprites you may have multiple sprites for one image. Consider creating an image pool to make sure you only load the image once. Then just point each Sprite object to the image within the pool that it requires. Your example in your question seems like you would more than likely load the same image into memory more than once. That's wasteful and could be part of the OutOfMemory issue.
于 2009-05-28T21:06:03.947 回答
1

使用电影图像(一个图像中定义尺寸的一组图像)并使用逻辑一次将它们拉出。

因为它们被分组到一个图像中,所以您可以节省每个图像的标题空间,从而可以减少使用的内存。

这种技术首先用于 MIDP 1.0 内存受限设备。

于 2009-06-04T10:52:39.983 回答
0

使用不反复加载图像的 Fostah 方法,我创建了以下类:

public class ImageLoader {
    private static Hashtable pool = new Hashtable();

    public static Image getSprite(String source){
        if(pool.get(source) != null) return (Image) pool.get(source);
        try {
            Image temp = Image.createImage(source);
            pool.put(source, temp);
            return temp;
        } catch (IOException e){
            System.err.println("Error al cargar la imagen en "+source+": "+e.getMessage());
        }
        return null;
    }
}

因此,每当我需要图像时,我首先会向池中请求它,或者只是将其加载到池中。

于 2009-05-29T00:14:27.450 回答