避免使用Handler而造成的記憶體洩漏

weixin_34007291發表於2016-05-19

原文連結

    public class SampleActivity extends Activity {                                                    /**   * Instances of static inner classes do not hold an implicit   * reference to their outer class.   */ 
                                    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);  /**   * Instances of anonymous classes do not hold an implicit   * reference to their outer class when they are static.   */  private static final Runnable sRunnable = new Runnable() {      @Override      public void run() { /* ... */ }  };  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    // Post a message and delay its execution for 10 minutes.    mHandler.postDelayed(sRunnable, 1000 * 60 * 10);        // Go back to the previous Activity.    finish();  }}

相關文章