现在的位置: 首页 > 综合 > 正文

Android中应用程序drawable图片资源占用内存的统计

2012年10月09日 ⁄ 综合 ⁄ 共 2225字 ⁄ 字号 评论关闭
在实际项目中,我们可能需要统计我们应用程序中drawable下的图片或文本在都载入的情况,最多会占用多少内存 ,以对其做定性分析。 

关于Android中图片占用内存的计算,请参照Android中图片占用内存的计算

以下就是一个简单的统计代码:

static void test(Context context){
    final String TAG="robin";
    long m=0;
    long n=0;
    Class c=R.drawable.class;
    Field f[]=c.getFields();
    int id=0;
    int w=0;
    int h=0;
    Resources res=context.getResources();
    for(int i=0;i<f.length;i++){
        try {
            id=f[i].getInt(null);
        } catch (IllegalArgumentException e) {
           
            e.printStackTrace();
        } catch (IllegalAccessException e) {
           
            e.printStackTrace();
        }
        Drawable d=res.getDrawable(id);
        if(d instanceof BitmapDrawable){
            Bitmap b=((BitmapDrawable)d).getBitmap();
            w=b.getWidth();
            h=b.getHeight();
            n=w*h;
            Log.i(TAG,"the size of "+f[i].getName()+" is "+w+"X"+h +" pixels");
            m=m+n;
        }
    }
    Log.i(TAG,"the area of all bitemap is "+m );
    m=m<<1;
    Log.w(TAG,"in Config.RGB_565,the memory occupied by bitemap:"+(m>>20)+"M"+((m&((1<<20)-1))>>10)+"K");
    m=m<<1;
    Log.w(TAG,"in Config.ARGB_8888,the memory occupied by bitemap:"+(m>>20)+"M"+((m&((1<<20)-1))>>10)+"K");
    c=R.string.class;
    f=c.getFields();
    String str=null;
    m=0;
    for(int i=0;i<f.length;i++){
        try {
            id=f[i].getInt(null);
        } catch (IllegalArgumentException e) {
           
            e.printStackTrace();
        } catch (IllegalAccessException e) {
           
            e.printStackTrace();
        }
        str=res.getString(id);
        m=m+str.length()*2;
    }
    Log.i(TAG,"string:"+(m>>20)+"M"+((m&((1<<20)-1))>>10)+"K"+(m&((1<<10)-1)));
}

运行结果:
I/robin   (21677): the size of app_detail_bottom_menu_divider is 3X5 pixels
I/robin   (21677): the size of cancel is 51X52 pixels
I/robin   (21677): the size of confirm is 51X52 pixels
I/robin   (21677): the size of ic_launcher is 96X96 pixels
I/robin   (21677): the size of item1 is 640X1067 pixels
I/robin   (21677): the size of item2 is 2560X1600 pixels
I/robin   (21677): the size of item3 is 2560X1600 pixels
I/robin   (21677): the size of item4 is 2560X1600 pixels
I/robin   (21677): the size of item5 is 2560X1600 pixels
I/robin   (21677): the size of item6 is 2560X1600 pixels
I/robin   (21677): the size of item7 is 2560X1600 pixels
I/robin   (21677): the size of splash is 640X1067 pixels
I/robin   (21677): the area of all bitemap is 25956295
W/robin   (21677): in Config.RGB_565,the memory occupied by bitemap:49M519K
W/robin   (21677): in Config.ARGB_8888,the memory occupied by bitemap:99M15K
I/robin   (21677): string:0M0K432
结束!

抱歉!评论已关闭.