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();
}
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'
}
低于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;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
当然最好让所有Activity继承一个BaseActivity Fragment继承一个BaseFragment,这样就会容易多了