引入LeakCanary到项目

引入LeakCanary到项目

1.在Application初始化(注意清单文件中Application的配置)

public static RefWatcher getRefWatcher(Context context) {
    MyApplication application = (MyApplication )context.getApplicationContext();
    return application.refWatcher;
}
private RefWatcher refWatcher;
private RefWatcher setupLeakCanary() {
    if (LeakCanary.isInAnalyzerProcess(this)) {
        return RefWatcher.DISABLED;
    }
    return LeakCanary.install(this);
}

public void onCreate() {
    super.onCreate();
    refWatcher= setupLeakCanary();
}

2.在module级别的build.gradle配置leakCanary(注意过低的版本会导致nullpointexception)

dependencies {
    ......

    //leak canary support
    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'
}

3.注意给应用附加读写SD卡权限 低于6.0版本直接加permission即可,大于等于6.0版本需要动态申请读写权限,否则会卡在拉取内存泄漏的popup处

低于6.0



大于等于6.0在第一个启动的Activity比如MainActivity申请权限(READ_EXTERNAL_STORAGE_REQUEST_CODE WRITE_EXTERNAL_STORAGE_REQUEST_CODE是自定义的int值)
在onCreate

if (!checkPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)) {
    requestPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE_REQUEST_CODE);
}

if (!checkPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
    requestPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
}
public void requestPermission(Activity activity,String permission,int reqestCode){
//第一次申请权限被拒后每次进入activity就会调用,或者用户之前允许了,之后又在设置中去掉了该权限
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
    Toast.makeText(activity, "XXX permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
    ActivityCompat.requestPermissions(activity,new String[]{permission},reqestCode);
}

}

回调可以知道是否申请成功

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case READ_EXTERNAL_STORAGE_REQUEST_CODE:
            Toast.makeText(this, "get read permission.", Toast.LENGTH_LONG).show();
            break;
        case WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
            Toast.makeText(this, "get write permission.", Toast.LENGTH_LONG).show();
            break;
    }
}

4.在要检测的Activity或者Fragment的onDestory加上内存泄漏检测

@Override
protected void onDestroy() {
    super.onDestroy();
    RefWatcher refWatcher = MyApplication.getRefWatcher(this);
    refWatcher.watch(this);
}

当然最好让所有Activity继承一个BaseActivity Fragment继承一个BaseFragment,这样就会容易多了

你可能感兴趣的:(Android)