今天就跟大家聊聊有關(guān)怎么在Android中利用LeakCanary對(duì)內(nèi)存泄漏進(jìn)行排查,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
創(chuàng)新互聯(lián)主營明水網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app開發(fā)定制,明水h5小程序定制開發(fā)搭建,明水網(wǎng)站營銷推廣歡迎明水等地區(qū)企業(yè)咨詢
在 build.gralde 里加上依賴, 然后sync 一下, 添加內(nèi)容如下
dependencies { .... debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' }
省略號(hào)代表其他已有內(nèi)容
在 Application類里面將 LeakCanary 初始化。。 比如叫MyApplication ,如果沒有就創(chuàng)建一個(gè),繼承 android.app.Application。 別忘了在AndroidManifest.xml中加上,否則不起作用
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return; } LeakCanary.install(this); // 你的其他代碼從下面開始 } }
官方已經(jīng)有demo了,可以跑跑看。
package com.github.pandafang.leakcanarytest; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View button = findViewById(R.id.async_task); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startAsyncTask(); } }); } void startAsyncTask() { // This async task is an anonymous class and therefore has a hidden reference to the outer // class MainActivity. If the activity gets destroyed before the task finishes (e.g. rotation), // the activity instance will leak. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Do some slow work in background SystemClock.sleep(20000); return null; } }.execute(); } }
進(jìn)入主界面按下按鈕, 再按返回鍵退出主界面, 反復(fù)幾次,LeakCanary 就能探測到內(nèi)存泄漏了。注意要多操作幾次,1次的話泄漏規(guī)模太小,可能不會(huì)探測到。LeakCanary 一旦探測到會(huì)彈出提示的。
回到桌面,會(huì)看到一個(gè)LeakCanary 的圖標(biāo),如果有多個(gè)app 用到就會(huì)有多個(gè)LeakCanary圖標(biāo)。
看完上述內(nèi)容,你們對(duì)怎么在Android中利用LeakCanary對(duì)內(nèi)存泄漏進(jìn)行排查有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
文章標(biāo)題:怎么在Android中利用LeakCanary對(duì)內(nèi)存泄漏進(jìn)行排查
本文URL:http://bm7419.com/article0/jdeeio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站改版、靜態(tài)網(wǎng)站、網(wǎng)站設(shè)計(jì)公司、品牌網(wǎng)站設(shè)計(jì)、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)