由于第一次在簡書寫文章将宪,如有寫的不好的地方,望海涵橡庞。
以前總是需要什么就去找什么较坛,自己一直沒有總結(jié)的強(qiáng)烈意識(shí),導(dǎo)致很多時(shí)候以前做過的東西扒最,現(xiàn)在需要丑勤,又得花時(shí)間去查詢。所以現(xiàn)在慢慢養(yǎng)成一種習(xí)慣同時(shí)為別人提供一種便利也是不錯(cuò)的方式吧趣。
這一篇講解的是leakcanary法竞,因?yàn)槲覀冊(cè)陂_發(fā)編碼過程中不可避免的會(huì)遇到一些內(nèi)存泄露的情況,雖然有一些地方是我們故意為之强挫,但還是有很多是在我們編寫代碼中產(chǎn)生的岔霸,但是只看代碼是很難查起,所以在此介紹一款相對(duì)較好俯渤,也使用比較多的一款內(nèi)存分析工具--leakcanary
對(duì)于這款工具的介紹各位就自己去網(wǎng)絡(luò)上找一些資料看看吧呆细,在此就不做過多介紹了,另外對(duì)于在AS上的使用八匠,直接從github導(dǎo)入就能使用絮爷,具體操作可以去網(wǎng)上看看趴酣,在此就不做過多介紹,補(bǔ)充leakcanary在AS使用地址:LeakCanary介紹
在此介紹的是leakcanary在eclipse中的使用坑夯,引用工程可以在下面地址進(jìn)行下載:LeakCanary依賴工程
1岖寞、添加依賴工程leakcanary-android
由于leackcanary-android工程依賴于leakcanary-analyzer,而leakcanary-analyzer工程又依賴于leakcanary-watch柜蜈。所以三個(gè)工程包都需要添加
2仗谆、在application 初始化leakcanary
import com.squareup.leakcanary.LeakCanary;
import android.app.Application;
public class MyApplication extends Application{
@Override
public void onCreate() {
// TODO Auto-generated method stub
LeakCanary.install(this);
super.onCreate();
}
}
3、在AndroidMainfest.xml 中配置
<!-- 相關(guān)的服務(wù)與Activity -->
<activity
android:name="com.squareup.leakcanary.internal.DisplayLeakActivity"
android:enabled="false"
android:icon="@drawable/leak_canary_icon"
android:label="@string/leak_canary_display_activity_label"
android:taskAffinity="com.squareup.leakcanary">
</activity>
<service
android:name="com.squareup.leakcanary.internal.HeapAnalyzerService"
android:enabled="false"
android:process=":leakcanary" />
<service
android:name="com.squareup.leakcanary.DisplayLeakService"
android:enabled="false" />
</application>
<!-- 寫權(quán)限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
4淑履、這個(gè)時(shí)候直接運(yùn)行測試工程隶垮,不停的跳Activity,出現(xiàn)內(nèi)存泄漏鳖谈,這個(gè)時(shí)候要等待一會(huì)哦,阔涉,你就會(huì)發(fā)現(xiàn)有通知欄缆娃,然后點(diǎn)擊就可以看到內(nèi)存泄漏堆棧關(guān)系了
當(dāng)然了,也可以在BaseActivity或者BaseFragment的onDestroy里面對(duì)這個(gè)類進(jìn)行監(jiān)控瑰排。
/**
* 初始化內(nèi)存泄露監(jiān)測 applicaton里面的代碼
*/
private void initRefWatcher() {
this.refWatcher = LeakCanary.install(this);
}
//BaseActivity或者BaseFragment的代碼
@Override
protected void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MentorNowApplication.getRefWatcher(this);
refWatcher.watch(this);
}