我相信已经成功安装了LeakCanary。
我将调试,发布和测试依赖项添加到build.gradle文件中。
我将必要的文件添加到我的应用程序类中。必要时进口。确认应用程序类已正确添加到清单中。我的应用程序类是否需要显式调用?
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
我在模拟器上运行我的应用程序,看不到任何不同。我监控Android监视器并没有看到任何区别。我怎么知道它是否全部有效?我已经分享了我的Application类。
import android.app.Application;
import android.content.res.Configuration;
import com.squareup.leakcanary.LeakCanary;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
return;
}
LeakCanary.install(this);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
答案 0 :(得分:5)
我的应用程序类是否需要显式调用?
没有
我怎么知道它是否全部有效?
故意泄漏某些东西。例如,将启动器活动实例分配给d:DataContext="{d:DesignInstance MockViewModels:MockMainWindowModel, IsDesignTimeCreatable=True}"
字段。
答案 1 :(得分:3)
首先,检查您是否连接到调试器? LeakCanary ignores leak detection when debugging以避免误报。
其次,Add the LeakCanary via Gradle然后执行以下操作:
class App : Application() {
companion object {
@JvmStatic
fun getRefWatcher(context: Context): RefWatcher {
val applicationContext = context.applicationContext as App
return applicationContext.refWatcher
}
}
private lateinit var refWatcher: RefWatcher
override fun 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;
}
refWatcher = LeakCanary.install(this)
}
}
在你的片段中(最好使用BaseFragment)
override fun onDestroy() {
if (BuildConfig.DEBUG) {
activity?.let {
App.getRefWatcher(it).watch(this)
}
super.onDestroy()
}
然后在你的一个带有片段的子活动中:
class MemLeakFragment : BaseFragment() {
companion object {
@JvmStatic
lateinit var memleak: Activity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.let {
memleak = it
}
}
}
使用memleak
碎片打开活动,然后用背面关闭它。等一下,LeakCanary会报告内存泄漏,这可能需要一段时间......