5

似乎 BitmapRegionDecoder 有内存泄漏。如果我运行下面的代码,我可以看到设备上的本机内存使用量增加。最终应用程序会因为崩溃而死掉,因为 Android 操作系统会因为缺少可用内存而终止它:

public void doClick(View v) {

    String bitmapFileName = "/mnt/sdcard/Wallpaper Images/-398300536.jpg";
    BitmapRegionDecoder dec;

    try {
        for (int i = 0; i < 100; i++) {

            FileInputStream is = new FileInputStream(bitmapFileName);
            dec = BitmapRegionDecoder.newInstance(is, false);

            // I am not even doing anything with bitmap region decoder!

            is.close();
            dec.recycle();
            System.gc();

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Running将在执行上述代码之前adb shell dumpsys meminfo报告以下内容(请参阅 3273 kB 的本机分配):

Applications Memory Usage (kB):
Uptime: 63276459 Realtime: 469577132

** MEMINFO in pid 27844 [com.example.test] **
                    native   dalvik    other    total
            size:     3284     5379      N/A     8663
       allocated:     3273     2831      N/A     6104
            free:       10     2548      N/A     2558
           (Pss):      600      779     2248     3627
  (shared dirty):       56     1256     5164     6476
    (priv dirty):      540       44     1036     1620

 Objects
           Views:        0        ViewRoots:        0
     AppContexts:        0       Activities:        0
          Assets:        2    AssetManagers:        2
   Local Binders:        5    Proxy Binders:       10
Death Recipients:        0
 OpenSSL Sockets:        0

 SQL
               heap:        0         MEMORY_USED:        0
 PAGECACHE_OVERFLOW:        0         MALLOC_SIZE:        0

在上面执行的代码adb shell dumpsys meminfo 之后运行报告分配了 12678kB 的本机内存!

 Applications Memory Usage (kB):
 Uptime: 63281361 Realtime: 469582034

 ** MEMINFO in pid 27844 [com.example.test] **
                     native   dalvik    other    total
             size:    12972     5379      N/A    18351
        allocated:    12678     2792      N/A    15470
             free:       33     2587      N/A     2620
            (Pss):      665      871    12411    13947
   (shared dirty):       56     1256     5560     6872
     (priv dirty):      612       48    10820    11480

  Objects
            Views:        0        ViewRoots:        0
      AppContexts:        0       Activities:        0
           Assets:        2    AssetManagers:        2
    Local Binders:        5    Proxy Binders:       11
 Death Recipients:        1
  OpenSSL Sockets:        0

  SQL
                heap:        0         MEMORY_USED:        0
  PAGECACHE_OVERFLOW:        0         MALLOC_SIZE:        0

这个问题似乎总是可以在 2.3.5 和 4.1.2 Android(物理设备)上重现。这个问题在 Android 模拟器上也总是可以重现的(我试过 Android 2.3.3)。我没有尝试过其他版本的Android,但我猜其他版本的问题也是一样的。

我做错了什么,还是recycle()BitmapRegionDecoder 的方法根本不起作用?

我怎样才能避免这个问题?

4

0 回答 0