Last active
October 31, 2019 22:10
-
-
Save anitaa1990/cb68057a174deba583dde4ace1ef038e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HandlersReferenceLeakActivity extends AppCompatActivity { | |
private TextView textView; | |
/* | |
* Fix number I | |
* */ | |
private final LeakyHandler leakyHandler = new LeakyHandler(this); | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_first); | |
leakyHandler.postDelayed(leakyRunnable, 5000); | |
} | |
/* | |
* Fix number II - define as static | |
* */ | |
private static class LeakyHandler extends Handler { | |
/* | |
* Fix number III - Use WeakReferences | |
* */ | |
private WeakReference<HandlersReferenceLeakActivity> weakReference; | |
public LeakyHandler(HandlersReferenceLeakActivity activity) { | |
weakReference = new WeakReference<>(activity); | |
} | |
@Override | |
public void handleMessage(Message msg) { | |
HandlersReferenceLeakActivity activity = weakReference.get(); | |
if (activity != null) { | |
activity.textView.setText(activity.getString(R.string.text_handler_2)); | |
} | |
} | |
} | |
private static final Runnable leakyRunnable = new Runnable() { | |
@Override | |
public void run() { /* ... */ } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What we have pass in run() method, how handleMessage(Message msg) triggered