dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
}
public class AppApplication 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);
// Normal app init code...
}
}
public class App extends Application {
//Application为整个应用保存全局的RefWatcher
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
App application = (App) context.getApplicationContext();
return application.refWatcher;
}
}
public abstract class BaseFragment extends Fragment {
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = App.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
public class TestHelper {
private Context mCtx;
private TextView mTextView;
private static TestHelper ourInstance = null;
private TestHelper(Context context) {
this.mCtx = context;
}
public static TestHelper getInstance(Context context) {
if (ourInstance == null) {
ourInstance = new TestHelper(context);
}
return ourInstance;
}
}
public class ContextLeakActivity extends AppCompatActivity{
private TestHelper mTestHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//这里容易引起内存泄漏
//我们在 ContextLeakActivity 里获取 TestHelper 实例时因为传入了 MainActivity 的 Context,
// 这使得一旦这个 Activity 不在了之后,
// TestHelper 依然会 hold 住它的 Context 不放,而这个时候因为 Activity 已经不在了,所以内存泄露自然就产生了。
mTestHelper=TestHelper.getInstance(this);
//避免内存泄漏的写法
// mTestHelper=TestHelper.getInstance(this.getApplication());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
getLocalBroadcastManager().unregisterReceiver(mExitReceiver);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有