package net.npaka.heapex; import java.nio.ByteBuffer; import java.util.ArrayList; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Debug; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout;
//ヒープ割当・解放のテストプログラム public class HeapEx extends Activity implements View.OnClickListener { private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT; private ArrayList<Bitmap> bitmaps=new ArrayList<Bitmap>(); private ArrayList<Object> objects=new ArrayList<Object>(); //初期化 @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); //レイアウトの生成 LinearLayout layout=new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255,255,255)); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); //ボタンの生成 layout.addView(makeButton("ネイティブヒープの負荷","nativeheap")); layout.addView(makeButton("Javaヒープの負荷","javaheap")); layout.addView(makeButton("解放","release")); layout.addView(makeButton("メモリ表示","memory")); } //ボタンの生成 private Button makeButton(String text,String tag) { Button button=new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } //ボタンクリック時に呼ばれる public void onClick(View view) { String tag=(String)view.getTag(); if (tag.equals("nativeheap")) { bitmaps.add(Bitmap.createBitmap(1024,1024/4,Bitmap.Config.ARGB_8888)); memory(this); } else if (tag.equals("javaheap")) { objects.add(ByteBuffer.allocate(1024*1024)); memory(this); } else if (tag.equals("release")) { bitmaps=new ArrayList<Bitmap>(); objects=new ArrayList<Object>(); memory(this); } else if (tag.equals("memory")) { memory(this); } } //メモリの出力 private void memory(Context context) { android.util.Log.e("debug","--------------------"); android.util.Log.e("debug","画像,オブジェクト>"+ bitmaps.size()+","+objects.size()); System.gc(); //Linuxヒープの空きサイズ ActivityManager.MemoryInfo info=new ActivityManager.MemoryInfo(); ActivityManager am=((ActivityManager)context. getSystemService(Activity.ACTIVITY_SERVICE)); am.getMemoryInfo(info); long linuxHeap=info.availMem; android.util.Log.e("debug","空きLinuxヒープ>"+ num2str(linuxHeap)); //アプリケーションヒープの利用サイズ long nativeHeap=Debug.getNativeHeapAllocatedSize(); Runtime runtime=Runtime.getRuntime(); long javaHeap=runtime.totalMemory()-runtime.freeMemory(); long appHeap=nativeHeap+javaHeap; android.util.Log.e("debug","アプリケーションヒープ(ネイティブ+Java)>"+ num2str(appHeap)+"("+num2str(nativeHeap)+"+"+num2str(javaHeap)+")"); } //数値→文字列 private String num2str(long num) { if (num<1024) return num+"B"; num/=1024; if (num<1024) return num+"KB"; num/=1024; return num+"MB"; } } |