学习内容来自文章:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0511/2861.html
为了学习,自己又徒手实现了一遍
1.AS中添加 依赖项
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
2.创建 Application 子类
public class MyApplication extends Application {
private RefWatcher mRefWatcher;
public MyApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = LeakCanary.install(this);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
3.AndroidManifest.xml文件中添加Application name
<application
android:name=".MyApplication"
android:allowBackup="true"
......
</application>
4.自定义类并实现单利模式
public class MyClass {
private static MyClass instance = null;
private Context context = null;
private TextView mTextView;
public static MyClass getInstance(Context context){
if(instance == null){
instance = new MyClass(context);
}
return instance;
}
private MyClass(Context context){
this.context = context;
}
private MyClass(){
}
public void setRetainedTextView(TextView tv){
this.mTextView = tv;
mTextView.setText(context.getString(android.R.string.ok));
}
}
5.实现MainActivity
public class MainActivity extends AppCompatActivity {
private RefWatcher mRefWatcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tv_test);
MyClass.getInstance(this).setRetainedTextView(tv);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
运行代码,按返回键会出现程序内存泄露对应的图标
内容简单,入门学习