首页 > 技术文章 > 释放内存的好方法

9420sunshine 2014-01-09 17:08 原文

 

释放应用的内存在退出activity的时候调用

private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}

调用方法

unbindDrawables(findViewById(R.id.root_view));
System.gc();

其中R.id.root_view为跟布局layout的id

http://stackoverflow.com/questions/1147172/what-android-tools-and-methods-work-best-to-find-memory-resource-leaks

 

//重启应用方法

Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

 

//使用bitmap时的最优方法

//图片加载时优化参数配置
public static Bitmap createBitmapbyDecodeStrream(Context context,int resId){
//图片加载优化
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPurgeable = true;// 允许可清除
options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果

return BitmapFactory.decodeStream(context.getResources().openRawResource(resId),null,options);
}

public static Bitmap createBitmapbyDecodeStrreamByTypeArray(Context context,int resId,TypedArray typedArray){
//图片加载优化
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPurgeable = true;// 允许可清除
options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果

return BitmapFactory.decodeStream((context.getResources().openRawResource(typedArray.getResourceId(resId,0))),null,options);
}

推荐阅读