Handler Should be static or leaks Occur?

Posted 小妖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Handler Should be static or leaks Occur?相关的知识,希望对你有一定的参考价值。

解决办法:

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<SampleActivity> mActivity;
         
    public MyHandler(SampleActivity activity) {
      mActivity = new WeakReference<SampleActivity>(activity);
    }
         
    @Override
    public void handleMessage(Message msg) {
      SampleActivity activity = mActivity.get();
      if (activity != null) {
        // ...
      }
    }
  }
         
  private final MyHandler mHandler = new MyHandler(this);

参考:android handler的警告Handler Class Should be Static or Leaks Occur

以上是关于Handler Should be static or leaks Occur?的主要内容,如果未能解决你的问题,请参考以下文章

Android Handler警告,SimpleDateFormat警告

FluentAssertions:ShouldBeEquivalentTo vs Should().Be() vs Should().BeEquivalentTo()?

[1.1]Knowledge that should be prepared

String literals should not be duplicated

Null pointers should not be dereferenced

"ISerializable" should be implemented correctly