Detailed explanation of Android Handler
We are often used to notify the main thread to perform corresponding operations, but if used, it will not only cause memory leakage, so record and write the correct Handler writing method.
Handler handler = new Handler() { public void handleMessage(Message msg) { //do something }; }; (0, 100 * 1000);
Like the code snippet above, there is a risk of memory leakage, because handler occupies the reference of Actvity, prevents the system from performing GC recycling operations.
private static class MyHandler extends Handler { WeakReference<MainActivity> mWeakReferenceActivity; public MyHandler(MainActivity activity) { mWeakReferenceActivity = new WeakReference<MainActivity>(activity); } @Override public void handleMessage(Message msg) { (msg); if (null != mWeakReferenceActivity) { MainActivity _activity = (); //_activity.dosomething(); } } }
The correct way is to store the stored Activity, so that when the Activity is finished recycling, WeakReference will not prevent the system from performing recycling operations, and can effectively avoid the risk of memory leakage caused by handlers.
Of course, it is not impossible to use handler writing. You need to enable the system to perform normal recycling operations when you end your activity.
The above is a detailed explanation of the usage of Android Handle and many articles on Android threads. There are many more on this site. You can refer to it. Thank you for reading it. I hope it can help you. Thank you for your support for this site!