前回の
の続きです。。
メモリリークの問題が出ていて、いろいろ調べていたのですが、
下記にカンタンな方法が記してありました。
OutOfMemoryError:Bitmapの使い方の問題?
上記でのメモリ解放の方法としては、
@Override protected void onDestroy() { super.onDestroy(); cleanupView(findViewById(R.id.root)); // ^^^^^^^^^^ ここはアクティビティのトップレベルレイアウトのIDを指定してください。 } /** * 指定したビュー階層内のドローワブルをクリアする。 * (ドローワブルをのコールバックメソッドによるアクティビティのリークを防ぐため) * @param view */ public static final void cleanupView(View view) { if(view instanceof ImageButton) { ImageButton ib = (ImageButton)view; ib.setImageDrawable(null); } else if(view instanceof ImageView) { ImageView iv = (ImageView)view; iv.setImageDrawable(null); } else if(view instanceof SeekBar) { SeekBar sb = (SeekBar)view; sb.setProgressDrawable(null); sb.setThumb(null); // } else if(view instanceof( xxxx )) { -- 他にもDrawableを使用するUIコンポーネントがあれば追加 } view.setBackgroundDrawable(null); if(view instanceof ViewGroup) { ViewGroup vg = (ViewGroup)view; int size = vg.getChildCount(); for(int i = 0; i < size; i++) { cleanupView(vg.getChildAt(i)); } }
がとても素敵な解放かと思います。
と言うかandroidでデフォルトでこの動作をしててくれてもいいのに。と思いました。
画像の参照をsetでnullしてあげる事によって、参照されていたbitmapが解放されるようになります。※すぐには解放されませんが放っておいて問題ないかと。。
すぐに解放する必要があればrecycleもできます。
DestroyはそのActivityが終了の時に実行されます。(finish()時など)