APP占用内存很大一部分是因为把图片读到缓存里面了,如果在关闭activity或者fragment或者dialog等的时候,不及时回收图片资源,就会越积越多,APP越来越卡。
解决办法:
及时recycle掉bitmap占用的内存
//缓存图片回收
public static void recycleBitmap(Drawable drawable){
if (drawable != null && drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
System.gc();
drawable = null;
}
}
}
public static void recycleBitmap(Drawable drawable){
if (drawable != null && drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
System.gc();
drawable = null;
}
}
}
这个方法需要传入drawable的参数,我们的imageView拥有获取drawable资源的方法:
private void recycleBitmap(){
for (int i = 0; i < expert_evaluate_pay_ima_layout.getChildCount(); i++) {
Drawable drawable = ((ImageView) expert_evaluate_pay_ima_layout.getChildAt(i)).getDrawable();
BitmapUtils.recycleBitmap(drawable);
}
}
for (int i = 0; i < expert_evaluate_pay_ima_layout.getChildCount(); i++) {
Drawable drawable = ((ImageView) expert_evaluate_pay_ima_layout.getChildAt(i)).getDrawable();
BitmapUtils.recycleBitmap(drawable);
}
}
这里一个带有7个imageView的linearLayout(layout的id忽略之。。),然后写个循环获取这个linearLayout里面的每一个imageView,然后调用imageView的getDrawable()方法就可以获得drawable对象啦~,然后销毁之就可以了。
这里有个问题!如果我们在xml布局文件里面设置了imageView的src(就是在xml声明imageView的图片)时,这时候如果我们在java代码里面调用recycleBitmap回收了imageView的图片资源后,我们如果再次打开这个activity/fragment时,重新加载xml文件进来时,会发现原本加载在xml的src上的图片现在并没有加载进来,说白了就是图片资源没有读进内存,app没有获取这张图片。
解决办法:不要在xml声明src资源,需要设置图片的地方可以用java代码动态加载进来:
private void setBitmap(){
int[] imas = new int[]{R.mipmap.expert_evaluate_pay_ima1,
R.mipmap.expert_evaluate_pay_ima2,
R.mipmap.expert_evaluate_pay_ima3,
R.mipmap.expert_evaluate_pay_ima4,
R.mipmap.expert_evaluate_pay_ima5,
R.mipmap.expert_evaluate_pay_ima6,
R.mipmap.expert_evaluate_pay_ima7,};
for (int i = 0; i < expert_evaluate_pay_ima_layout.getChildCount(); i++) {
InputStream is = getResources().openRawResource(imas[i]);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
((ImageView)expert_evaluate_pay_ima_layout.getChildAt(i)).setImageBitmap(mBitmap);
}
}
int[] imas = new int[]{R.mipmap.expert_evaluate_pay_ima1,
R.mipmap.expert_evaluate_pay_ima2,
R.mipmap.expert_evaluate_pay_ima3,
R.mipmap.expert_evaluate_pay_ima4,
R.mipmap.expert_evaluate_pay_ima5,
R.mipmap.expert_evaluate_pay_ima6,
R.mipmap.expert_evaluate_pay_ima7,};
for (int i = 0; i < expert_evaluate_pay_ima_layout.getChildCount(); i++) {
InputStream is = getResources().openRawResource(imas[i]);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
((ImageView)expert_evaluate_pay_ima_layout.getChildAt(i)).setImageBitmap(mBitmap);
}
}
这里我用for循环将bitmap一个一个设置进入imageView,只要在oncreate方法里面调用setBitmap方法就可以利用java代码动态添加图片了,而不是写在xml的src里面。