我有一个复杂的战斗系统,它有一个父活动和几个子类,这些子类通过扩展Battle并将上下文传递给这些类来访问BattleActivity的静态变量。
这一切似乎都很好,但是我在释放所有AnimationDrawables的内存方面遇到了问题。在一场战斗中可能会使用24个DrawableAnimations。目前还可以,但每当用户遇到新怪物时,就会向内存中添加4个AnimationDrawables,这将慢慢地导致我的应用程序因为内存不足而崩溃。
因此,我真的需要找到一种方法,尽快释放战斗系统占用的所有内存。目前,我正在Sony Z2上进行测试,当用户进入战斗时,内存从91mb增加到230mb。当战斗完成后,我需要将内存使用量降回到91mb。我已经添加了一些非常基本的代码片段,以便让您了解应用程序当前的流程以及我试图做什么来释放内存。
这一切似乎都很好,但是我在释放所有AnimationDrawables的内存方面遇到了问题。在一场战斗中可能会使用24个DrawableAnimations。目前还可以,但每当用户遇到新怪物时,就会向内存中添加4个AnimationDrawables,这将慢慢地导致我的应用程序因为内存不足而崩溃。
因此,我真的需要找到一种方法,尽快释放战斗系统占用的所有内存。目前,我正在Sony Z2上进行测试,当用户进入战斗时,内存从91mb增加到230mb。当战斗完成后,我需要将内存使用量降回到91mb。我已经添加了一些非常基本的代码片段,以便让您了解应用程序当前的流程以及我试图做什么来释放内存。
public class Battle extends Activity
{
// I have several AnimationDrawables loaded into memory
// These are then assigned the relevent animation to a button swicthing between these animations throughout my battle
ImageButton btnChr1;
AnimationDrawable cAnimHit1;
}
//This is the use of one of those AnimationDrawables
public class Battle_Chr_Anim extends Battle
{
protected Context ctx;
private ImageButton btnChr1;
AnimationDrawable cAnimHit1;
public Battle_Chr_Anim(Context c, ImageButton _btnChr1, AnimationDrawable _cAnimHit1) {
this.ctx = c;
this.btnChr1 = _btnChr1;
this.cAnimHit1 = _cAnimHit1;
}
// Bound the ImageButton
int id = ctx.getResources().getIdentifier("idle", "drawable", ctx.getPackageName());
img_chr1.setBackgroundResource(id);
frameAnimation = (AnimationDrawable)img_chr1.getBackground();
frameAnimation.start()
// Loaded into memory ready so I can swicth them over quickly when user attacks
int ca1 = ctx.getResources().getIdentifier("attack", "drawable", ctx.getPackageName());
cAnimHit1 = (AnimationDrawable)chrHit1.getBackground();
cAnimHit1.start();
}
public class Battle_Ended extends Battle
{
protected Context ctx;
public Battle_Ended(Context c) {
this.ctx = c;
}
//This is a dialog popup when the user completes the battle closing the battle activty
void EndBattle()
{
ImageButton btnSubmit = (ImageButton)dialog.findViewById(R.id.imgBtnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
RecyleAllAnimations();
dialog.dismiss();
((Activity) ctx).finish();
}
});
}
void RecyleAllAnimations()
{
// I want all AnimationDrawables from memory here, I believe the below line removes the one currently in use, however I have no way of releasing the other animations sitting in memory.
img_chr1.setBackgroundResource(android.R.color.transparent);
System.gc();
}
}