关于利用 LeakCanary 来检查 Android 内存泄漏
源码:https://github.com/square/leakcanary
第一步:添加依赖
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' }
第二步:在application类中初始化LeakCanary
import android.app.Application; import android.content.Context; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; /** * Created by Administrator on 2017/1/18. */ public class MyApplication extends Application { /** * ActivityRefWatcher 来监控 Activity 泄漏。即当 Activity.onDestroy() 被调用之后, * 如果这个 Activity 没有被销毁,logcat 就会打印出如下信息告诉你内存泄漏发生了。 * @param context * @return */ public static RefWatcher getRefWatcher(Context context){ MyApplication myApplication= (MyApplication) context.getApplicationContext(); return myApplication.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); //初始化refWatcher refWatcher=LeakCanary.install(this); } }
第三步:在AndroidManifest.xml使用上一步的application类
<application
//此处使用自定义的application类 android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity"></activity> </application>
第四步:在activity中使用LeakCanary来监测内存泄漏情况,在onCreate()方法中初始化
//<!-- LeakCanary --> //应用初始Activity中加入如下两行代码 RefWatcher refWatcher = UILApplication.getRefWatcher(this); refWatcher.watch(this); //<!-- LeakCanary -->
在Fragment中监控泄漏
public abstract class BaseFragment extends Fragment { @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity()); refWatcher.watch(this); } }
OK,完成了,如果有内存泄露的话就会自动提示,上效果图。
测试代码:静态变量引用非静态资源就很容易引起内存泄漏
public class SecondActivity extends AppCompatActivity { static Demo sDemo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); RefWatcher refWatcher=MyApplication.getRefWatcher(this); refWatcher.watch(this); if (sDemo == null) { sDemo = new Demo(); } finish(); } class Demo { void doSomething() { System.out.print("===============dosth.=========="); } } }
参考资料:
http://blog.csdn.net/jie1991liu/article/details/49927865