Android 内存泄漏

LeakCanary

监测应用内存泄露的轻量级工具,方便集成,简洁清晰。

LeakCanary简单集成:

  1. 在build.gradle中加入对应依赖:

     dependencies {
                  debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
                   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
     }
    
  2. 在Application的onCreate方法中加入 LeakCanary.install(this):

     public class ExampleApplication extends Application {
                @Override 
                public void onCreate() {
                              super.onCreate();
                              LeakCanary.install(this);
                  }
        }
    

Hander导致的内存泄漏解决

           public class SampleActivity extends Activity {

                     private static class MyHandler extends Handler {
                             private final WeakReference mActivity;

                             public MyHandler(SampleActivity activity) {
                                    mActivity = new WeakReference(activity);
                             }

                             @Override
                             public void handleMessage(Message msg) {
                                   SampleActivity activity = mActivity.get();
                                   if (activity != null) {
                                                      // ...
                                        }
                              }
                     }
      
                     private final MyHandler mHandler = new MyHandler(this);

                     private static final Runnable sRunnable = new Runnable() {
                                      @Override
                                      public void run() { /* ... */ }
                     };

                     @Override
                     protected void onCreate(Bundle savedInstanceState) {
                             super.onCreate(savedInstanceState);

                             mHandler.postDelayed(sRunnable, 1000 * 60 * 10);
                      }
            }

参考链接

LeakCanary 中文使用说明
Github: leakcanary

你可能感兴趣的:(Android 内存泄漏)