我有一個複雜的戰鬥系統,它有一個父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