Stuck at “Dumping memory, app will freeze. Brrr.”

2020-06-07 06:38发布

问题:

I'm trying to use LeakCanary to detect memory leaks in my app, but it does not go further than the message "Dumping memory, app will freeze. Brrr." I've been waiting for about 20 minutes or so, but no changes. Same behaviour on these devices: 1. Asus fonepad 8 (Android 5.0 stock) 2. Sony Xperia SP (Android 5.1.1 CM 12.1 custom) 3. HTC Desire C (Android 4.4 CM 11 custom)

I did everything as its advised in instruction:

public class ExampleApplication extends Application {

  @Override public void onCreate() {
    super.onCreate();
    LeakCanary.install(this);
  }
}

回答1:

If you're on Android M you need to grant the "write external storage" permission or leak canary will hang for a long time with the brrr message. In your apps drawer, long click on the launcher for leak canary (like you were going to uninstall it) and drag up to "app info" and turn on the storage permission.



回答2:

You should add the RefWatcher to your fragment as well just like what is described on the project page: https://github.com/square/leakcanary

LeakCanary.install() returns a pre configured RefWatcher. It also installs an ActivityRefWatcher that automatically detects if an activity is leaking after Activity.onDestroy() has been called.

public class ExampleApplication extends Application {

  public static RefWatcher getRefWatcher(Context context) {
    ExampleApplication application = (ExampleApplication) context.getApplicationContext();
    return application.refWatcher;
  }

  private RefWatcher refWatcher;

  @Override public void onCreate() {
    super.onCreate();
    refWatcher = LeakCanary.install(this);
  }
}

You could use the RefWatcher to watch for fragment leaks:

public abstract class BaseFragment extends Fragment {

  @Override public void onDestroy() {
    super.onDestroy();
    RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
    refWatcher.watch(this);
  }
}

Besides, if you want to get the heap dump when memory leak happened, just open the Android Device Monitor from Android Studio, and select the tab "File Explorer". In the directory /mnt/shell/emulated/0/Download/leakcanary/detected_leaks, you will find all the heap dump files.