我有一个复杂的战斗系统,它有一个父Activity和几个子类,它们通过扩展Battle并将上下文传递给这些类来访问BattleActivity的静态变量。Android - 释放分配的内存AnimationDrawable正在使用
这一切似乎工作正常,但我有一个从内存释放我所有的AnimationDrawables问题。在战斗中总共可以使用24个DrawableAnimations。目前这是可以的,但是每当用户遇到新的怪物时,就会有4个AnimationDrawables被添加到内存中,这会缓慢但随意地导致我的应用程序崩溃并导致anb内存不足异常。
因此,我真的需要找到一种方法来释放我的战斗系统在我退出后立即占用的所有内存。目前,我正在索尼Z2上进行测试,当用户进入战斗时,mmeory从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();
}
}
你真的有静态变量,你传递的应用程序上下文?我认为他们会比你的drawables更早地杀死你的应用程序 – TheRedFox 2014-11-07 14:37:06
是的,这仅仅是为了我的对战方面的事情,因为我不想让我所有的代码都在同一个Activity中,只是扩展这个类,以便我仍然可以访问UI。由于我需要能够加载所有的AnimationDrawables之前加载活动,以便动画可以流利当用户进入战斗 – 2014-11-07 14:43:44