首页 > 系统 > Android > 正文

利用 LeakCanary 来检查 Android 内存泄漏

2019-11-06 09:48:20
字体:
来源:转载
供稿:网友

LeakCanary简介

LeakCanary是一款开源的内存泄露检测工具。开源代码被github托管。地址:https://github.com/SOFTPOWER1991/leakcanarySample_androidStudio有些对象只有有限的生命周期。当它们的任务完成之后,它们将被垃圾回收。如果在对象的生命周期本该结束的时候,这个对象还被一系列的引用,这就会导致内存泄漏。随着泄漏的累积,app将消耗完内存。

android stdio 接入方式

1.android stdio 将工程切到android模式,在build.gradle(module模式下)添加依赖: 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' }2.要监控Activity泄露,自定义applicationpublic class MyApplication extends Application { PRivate static final String TAG = "MyApplication"; public static RefWatcher getRefWatcher(Context context) { MyApplication application = (MyApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { Log.i(TAG,"onCreate first called............"); super.onCreate(); refWatcher = LeakCanary.install(this); }}3.在AndroidManifest.xml配置文件中声明MyApplication<application android:name=".MyApplication" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/APPTheme">4.一个测试的例子public class SecondActivity extends AppCompatActivity { static Demo sDemo; private static final String TAG = "SecondActivity"; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG,"onCreate() is called!!!!!!!!!!!!!!!!"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); if (sDemo == null) { sDemo = new Demo(); } finish(); } class Demo { private ArrayList<String> a = new ArrayList<String>(); public Demo() {} }}5.执行后结果:

内存泄露的场景举例


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表