LoginSignup
13
10

More than 5 years have passed since last update.

Picasso が利用するメモリのサイズを変更する

Last updated at Posted at 2015-11-26

Picasso が使用するのはデフォルトだと端末で使用できるメモリの 15% だが、メモリ圧迫?のせいか java.lang.OutOfMemoryError が多発するようになってしまったので 10% に変更してみた。

前提:

Piccsso のバージョン:2.5.2

手元の Android アプリケーション

  • compileSdkVersion 22
  • minSdkVersion 15
  • targetSdkVersion 22
  • LargeHeap を有効にしている
    • つまり AndroidManifest.xmlandroid:largeHeap="true" としている

まず Piacasso のソースの Utils.java を見ると、デフォルトの 15% というのは次のように計算している。

Utils.java
// ..

static int calculateMemoryCacheSize(Context context) {
  ActivityManager am = getService(context, ACTIVITY_SERVICE);
  boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
  int memoryClass = am.getMemoryClass();
  if (largeHeap && SDK_INT >= HONEYCOMB) {
    memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
  }
  // Target ~15% of the available heap.
  return 1024 * 1024 * memoryClass / 7;
}

// ..

上記を見る限り、7 で割ってるので、厳密には 15% でなく 14.28% ぐらいだと思われる。

これを参考に、自分のアプリケーションに適用してみる。カスタム Application クラスの onCreate() で、

MyApplication.java
// ..

@Override
public void onCreate() {
    super.onCreate();

    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    boolean largeHeap = (getApplicationInfo().flags & ApplicationInfo.FLAG_LARGE_HEAP) != 0;
    int memoryClass = am.getMemoryClass();
    if (largeHeap && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        memoryClass = am.getLargeMemoryClass();
    }
    int cacheSize = 1024 * 1024 * memoryClass / 10;
    Picasso picasso = new Picasso.Builder(this).memoryCache(new LruCache(cacheSize)).build();
    Picasso.setSingletonInstance(picasso);
}

// ..

以上。

13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10