在android中context可以作很多操作,但是最主要的功能是加載和訪問資源。在android中有兩種context,一種是 application context,一種是activity context,通常我們?cè)诟鞣N類和方法間傳遞的是activity context。
比如一個(gè)activity的onCreate:
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this); //傳遞context給view control
label.setText("Leaks are bad");
setContentView(label);
}
把a(bǔ)ctivity context傳遞給view,意味著view擁有一個(gè)指向activity的引用,進(jìn)而引用activity占有的資源:view hierachy, resource等。
這樣如果context發(fā)生內(nèi)存泄露的話,就會(huì)泄露很多內(nèi)存。
這里泄露的意思是gc沒有辦法回收activity的內(nèi)存。
Leaking an entire activity是很容易的一件事。
當(dāng)屏幕旋轉(zhuǎn)的時(shí)候,系統(tǒng)會(huì)銷毀當(dāng)前的activity,保存狀態(tài)信息,再創(chuàng)建一個(gè)新的。
比如我們寫了一個(gè)應(yīng)用程序,它需要加載一個(gè)很大的圖片,我們不希望每次旋轉(zhuǎn)屏 幕的時(shí)候都銷毀這個(gè)圖片,重新加載。實(shí)現(xiàn)這個(gè)要求的簡(jiǎn)單想法就是定義一個(gè)靜態(tài)的Drawable,這樣Activity 類創(chuàng)建銷毀它始終保存在內(nèi)存中。
實(shí)現(xiàn)類似:
public class myactivity extends Activity {
private static Drawable sBackground;
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);//drawable attached to a view
setContentView(label);
}
}
這段程序看起來很簡(jiǎn)單,但是卻問題很大。當(dāng)屏幕旋轉(zhuǎn)的時(shí)候會(huì)有l(wèi)eak(即gc沒法銷毀activity)。
我們剛才說過,屏幕旋轉(zhuǎn)的時(shí)候系統(tǒng)會(huì)銷毀當(dāng)前的activity。但是當(dāng)drawable和view關(guān)聯(lián)后,drawable保存了view的 reference,即sBackground保存了label的引用,而label保存了activity的引用。既然drawable不能銷毀,它所 引用和間接引用的都不能銷毀,這樣系統(tǒng)就沒有辦法銷毀當(dāng)前的activity,于是造成了內(nèi)存泄露。gc對(duì)這種類型的內(nèi)存泄露是無能為力的。
避免這種內(nèi)存泄露的方法是避免activity中的任何對(duì)象的生命周期長(zhǎng)過activity,避免由于對(duì)象對(duì) activity的引用導(dǎo)致activity不能正常被銷毀。我們可以使用application context。application context伴隨application的一生,與activity的生命周期無關(guān)。application context可以通過Context.getApplicationContext或者Activity.getApplication方法獲取。
避免context相關(guān)的內(nèi)存泄露,記住以下幾點(diǎn):
1. 不要讓生命周期長(zhǎng)的對(duì)象引用activity context,即保證引用activity的對(duì)象要與activity本身生命周期是一樣的
2. 對(duì)于生命周期長(zhǎng)的對(duì)象,可以使用application context
3. 避免非靜態(tài)的內(nèi)部類,盡量使用靜態(tài)類,避免生命周期問題,注意內(nèi)部類對(duì)外部對(duì)象引用導(dǎo)致的生命周期變化
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。